1

We've 700 static HTML files in folder "music". We want to put analytic code in the end of the HTML files.. like before

</body> </html>

tags.

Please anybody let me know, how its possible with PHP code?

4
  • 2
    loop through the files in that directory, open each in turn, use DomDocument to inject the additional markup you want, and write it back to the same filename Commented Mar 7, 2013 at 10:01
  • Also you may want to think over your data storage and move your content to a kind of database and generate your static files out of it. Commented Mar 7, 2013 at 10:02
  • do you want to add some html codes or php codes? Commented Mar 7, 2013 at 10:05
  • 1
    Sounds like you need a footer template :-) Commented Mar 7, 2013 at 11:34

1 Answer 1

2

Too easy. Find all files, read content, modify content, save content.

<?php

// open directory
if($handle = opendir(__DIR__)) {
    // search for
    $search = '</body>';

    // replace with (</body> gets appended later in the script)
    $replace = <<< EOF

<!-- your analytics code here -->

EOF;

    // loop through entries
    while(false !== ($entry = readdir($handle))) {
        if(is_dir($entry)) continue; // ignore entry if it's an directory

        $content = file_get_contents($entry); // open file
        $content = str_replace($search, $replace . '</body>', $content); // modify contents
        file_put_contents($entry, $content); // save file
    }
}

echo 'done';

?>
Sign up to request clarification or add additional context in comments.

6 Comments

You probably meant str_replace rather than preg_replace, given the contents of $search.
i've put index.php file in my html folder, when i tested this code, html files are blank, its show Warning: file_put_contents() expects at least 2 parameters, 1 given in C:\wamp\www\html\index.php on line 25,
Guys you are too fast! Congrats. No need to write more
@user1218948 My apologies. As the error mentions, file_put_contents requires two parameters instead of one. I have edited the code. I surely hope you have a backup of the old html files :(
Tim, thanks for code, yeah its working for me, but code puts two extra Angle brackets on Analytic script? why its happen?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.