Forum Moderators: coopster

Message Too Old, No Replies

Insert Content Into HTML Files w/PHP

         

eslobrown

3:28 pm on Dec 20, 2009 (gmt 0)

10+ Year Member



Hello All,

I have a list of files in a directory, the file names of which are sequential (1.html through 100.html).

Is it possible to create a script that will open each of the files and insert content right after the open <body> tag?

Thanks in advance,

Eslo Brown

ALKateb

4:51 pm on Dec 20, 2009 (gmt 0)

10+ Year Member



you have list of files you want to loop through? replacing all between the body tags? then write these changes to the file
if that is what you want to do then here is how to do it

//get the file contents
$file = file_get_contents("somehtml.html");
//use regex to replace what's in between the body tags
$file = preg_replace("/\<body\>(.*)\<\/body\>/Uis","<body>something inside body</body>", $file);

//open the file in write mode
$myFile = "somehtml.html";
$fh = fopen($myFile, 'w') or die("can't open file");
//write the new contents to the file
fwrite($fh, $file);
fclose($fh);

if that is what you wanted to do then you can do it like i explained above you just need to define an array with your files names and then loop through this array

ALKateb

4:58 pm on Dec 20, 2009 (gmt 0)

10+ Year Member



i figured maybe u meant to add something after the opening body tag?
if yes then you do this instead

$file = file_get_contents("somehtml.html");
$file = str_replace("<body>","<body>something you wanna add here", $file);

$myFile = "somehtml.html";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $file);
fclose($fh);

eslobrown

5:16 pm on Dec 20, 2009 (gmt 0)

10+ Year Member



Hey ALKateb,

Thanks for the reply.

I'm making a noob attempt to add the loop portion. Let me know if I'm even close:

<?php
$a= 1;
$b= 10;
while ($a <= $b) {
$file = file_get_contents("$a.html");
$file = str_replace("<body>","<body>something you wanna add here", $file);

$myFile = "$a.html";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $file);
fclose($fh);

$a++;
}
?>

ALKateb

5:23 pm on Dec 20, 2009 (gmt 0)

10+ Year Member



this should work and if not please post part of your html file

eslobrown

7:47 pm on Dec 20, 2009 (gmt 0)

10+ Year Member



Works perfectly ALKateb. Thanks!