Log in

View Full Version : php load external html into variable question - beginner



grumsterUK99
01-23-2008, 04:57 PM
Hi all.

I would like to load a php variable with HTML markup that is stored in an external text file and then pass this markup to the innerHtml of a DIV element.

I have this code:

<?php

$textfile="textfile.txt";
$handle = fopen($textfile, "r");
$contents = fread($handle,filesize($textfile));

fclose($handle);


?>

div = document.getElementById('contentdiv');
div.innerHTML = '<?php print $contents; ?>';

This is not working.
I have tried with a plain text also, so I guess it has something to do
with the way the file is read into the variable.
I have tried hardcoding $content="Text" and it works as expected, so I know the markup is correct.

Can anyone help me out with this?

Thanks a lot for your time.

thetestingsite
01-23-2008, 05:25 PM
Well, you could try the following:



<?php
$content = file_get_contents('textfile.txt');
?>


Then using the javascript you can do this:



div = document.getElementById('contentdiv');
div.innerHTML = '<?php echo $content; ?>';


Hope this helps.

grumsterUK99
01-23-2008, 05:42 PM
thetestingsite - Thanks for the reply - but this doesn't seem to work either.
I am using just plain text in the external file to test it.

thetestingsite
01-23-2008, 06:18 PM
Are you using the same code (the two posted above) on the same page? Also, do you have a link to the problem page?

grumsterUK99
01-23-2008, 11:35 PM
Thanks for the reply.
I had a syntax error in my code :o

The plain text in the file is working but I could still not
get html to display correctly.
However, I have discovered various reasons for this including:

quotes in the HTML string need to be escaped with \;
carriage returns and other unwanted character codes need to be removed;
the HTML needs to be on one line;

If I stick to these rules it seems to be ok.

Thanks very much for your help thetestingsite