Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    Sep 2002
    Location
    Wilsonville, Oregon
    Posts
    17
    Thanks
    0
    Thanked 0 Times in 0 Posts

    parsing a text file for a tag?

    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 Code:
    <?php

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

    ?>
    can anyone tell what I am doing wrong?

  • #2
    Supreme Overlord Spookster's Avatar
    Join Date
    May 2002
    Location
    Marion, IA USA
    Posts
    6,273
    Thanks
    4
    Thanked 83 Times in 82 Posts
    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.
    Spookster
    CodingForums Supreme Overlord
    All Hail Spookster

  • #3
    New Coder
    Join Date
    Sep 2002
    Location
    Wilsonville, Oregon
    Posts
    17
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thank you, that worked. However, the way I was doing it before, was appending the file, for instance, If I went with

    PHP Code:
    $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 Code:
    <?php

    // opens file, rips data from it

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

    // 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?

  • #4
    Regular Coder
    Join Date
    Jun 2002
    Location
    Sheffield, UK
    Posts
    552
    Thanks
    0
    Thanked 0 Times in 0 Posts
    just open the file as r+, this allows reading and writing to the file.

    http://www.php.net/fopen for full syntax list
    "To be successful in IT you don't need to know everything - just where to find it in under 30 seconds"

    (Me Me Me Me Me Me Me Me Me)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •