How can I open an HTML file, modify it and then save it ?

Discussion in 'PHP' started by countrydj, Mar 30, 2011.

  1. #1
    Hi Guys...

    I am using a php5 script.

    I want to open an html file then find some text then replace that text with new text and then save the file.

    e.g.
    File to open: webstats.html
    Text to find: "gensumtitle"
    Text to replace it: 'gensumtitle'
    Save file to: webstats.html

    I'm sure that it is fairly simple, but I just can't figure it out.

    Any help would be appreciated.

    John C
     
    countrydj, Mar 30, 2011 IP
  2. Muggles

    Muggles Peon

    Messages:
    13
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Something along the lines of this:

    
    <?php
    // Load current contents of the file to the variable $contents
    $contents = file_get_contents("webstats.html");
    // Use str_replace to replace all occurrences of "gensumtitle" and replace it with 'gensumtitle'
    $contents = str_replace("\"gensumtitle\"", "'gensumtitle'", $contents);
    // Write the new contents to the file
    file_put_contents("webstats.html", $contents);
    ?>
    
    PHP:
     
    Muggles, Mar 30, 2011 IP
  3. countrydj

    countrydj Active Member

    Messages:
    41
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    91
    #3
    Hi Muggles...

    Many thanks for your very quiock reply.

    I made a very silly mistake and spent hours trying to figure it out.

    This was existing code:
    # get the webstats.html file
    $statfile="logs/webstats.html";


    This is where I was up to:
    $file = file_get_contents($statfile);
    $file = str_replace("gensumtitle", 'gensumtitle', $file);
    file_put_contents($statfile, $file);


    This is the modifeid script with thanks to you:
    $file = file_get_contents($statfile);
    $file = str_replace("\"gensumtitle\"", "'gensumtitle'", $file);
    file_put_contents($statfile, $file);


    I didn't put the str_replace variables in quotes, nor did I delimit the quotes in the first variable.

    Very many thanks for taking the time and trouble to help and advise me.

    THANK YOU...

    John C
     
    countrydj, Mar 30, 2011 IP