...

View Full Version : parsing a text file for a tag?



Heywood
07-02-2003, 05:11 AM
Basically, what I am trying to do is open a .htm file, and parse it for a custom tag, and replace that tag with another chunk of text. For instance, a <logo> tag would be replaced with the actual code to put in my logo. Here is what I have so far, and its not working. In fact, it isn't doing much of anything:



<?php

$file = fopen ("test.htm","a+");
$data = fread($file, 10000);
str_replace("<SPECIAL>", "<REPLACED>", $data);
fclose($file);

?>


can anyone tell what I am doing wrong?

Spookster
07-02-2003, 05:32 AM
str_replace does not write to the file. You need to write your changes to the file. Start by storing your changes in a variable:

$data = str_replace("<SPECIAL>", "<REPLACED>", $data);

then write the contents of $data back to your file using either fwrite or fputs.

Heywood
07-02-2003, 06:54 AM
Thank you, that worked. However, the way I was doing it before, was appending the file, for instance, If I went with


$file = fopen("test.htm","a+");

it would append it to the end. If I went with "w", it would clear it out. So, my solution was this:




<?php

// opens file, rips data from it

$file = fopen("test.htm","r");
$data = fread($file, 10000);

// closes file

fclose($file);

// re-opens file, clears all data
$file = fopen("test.htm","w+");

// replaces special tag with our code

$data = str_replace("<SPECIAL>", "REPLACED", $data);

// writes and closes

fwrite($file, $data);
fclose($file);

?>


Which is functional, but I am not sure if this is the best way to do it. Should I open the file twice like this? What do you think?

ReadMe.txt
07-02-2003, 10:17 PM
just open the file as r+, this allows reading and writing to the file.

http://www.php.net/fopen for full syntax list



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum