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

07-02-2003, 06: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:


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


can anyone tell what I am doing wrong?

07-02-2003, 06: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.

07-02-2003, 07: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:


// opens file, rips data from it

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

// closes 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);


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?

07-02-2003, 11: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