Page 1 of 1

Simple Question: How to add to an HTML file from a PHP file

Posted: Sun Apr 13, 2003 12:58 pm
by glim
Hello everyone. I'm new to PHP, and have a simple question:

I have an HTML file called "myFile.html"
I have a PHP file called "add.php"

How would I code it so that "add.php" adds the line "<p>Hello!</p>" to "myFile.html"?

Thanks!

Posted: Sun Apr 13, 2003 1:27 pm
by McGruff
If you want to output some vars created in a php file try adding this to the html file:

Code: Select all

<?php
include('folder_1/folder_2/..etc../add.php');
echo $var;
?>
Or, include the html file in add.php:

Code: Select all

<?php

..your code in add.php which defines $var1, $var2 etc..

include('folder_1/folder_2/..etc../myfile.html');
?>
Then, in myfile.html add the vars anywhere you like with:

Code: Select all

<?php echo $var1; ?>
The include has to come after you have declared the vars, of course.

Posted: Mon Apr 14, 2003 8:55 pm
by glim
Well, I got it working. Here's the code I wrote:

Code: Select all

<?php

	$handle = fopen('myDoc.html', 'r+');
	
	if ($handle) {

		if (fseek($handle,1) == 0) {
			fwrite($handle,'<p>I WAS HERE!!');
		}
		fclose($handle);
	}

?>
But I have a problem, this method erases the existing characters instead of inserting them. Is there a way to change that?

Thanks!

Posted: Mon Apr 14, 2003 8:59 pm
by volka
http://www.php.net/manual/en/function.fopen.php wrote:'r+' - Open for reading and writing; place the file pointer at the beginning of the file.
...
'a' - Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

Posted: Mon Apr 14, 2003 9:25 pm
by glim
I tried using 'a' but I couldn't move the file pointer. My HTML file looks like:

Code: Select all

<HTML>
<BODY>
asdasdasdasd
!!!
</BODY>
</HTML>
I want to put 'I WAS HERE' right after the exclamation marks, without erasing what comes after.

Thanks.

Posted: Mon Apr 14, 2003 9:45 pm
by volka
there are no file functions to really insert something but you might set the file-pointer to the position, write the new data and append what has been overwritten, e.g.

Code: Select all

<?php
// the static footer of the page written by this script
$footer = '</BODY></HTML>';
// open the exisiting document
$fp = fopen('test.html', 'r+');
// set the file pointer to the current position of the static footer
fseek($fp, -strlen($footer), SEEK_END);
// overwrite/append something
fwrite($fp, date("H:i:s")."<br />\n");
// add the footer
fwrite($fp, $footer);
// close the file because...
fclose($fp);
//... it is included here
include('test.html');
?>