Page 1 of 1

loadHTMLFile for PHP files

Posted: Sun Feb 02, 2014 10:44 pm
by iSofia
Hello everyone. I am trying to add some dynamic content to a page that contains PHP code. When I use the loadHTMLFile function to do this, the PHP tags <?PHP ?> are replaced by &lt?php ?&gt, corrupting it. It also raises a whole bunch of DOMDocument::loadHTMLFile(): htmlParseEntityRef: no name in... errors. All I'm trying to do is add some checkboxes to the page according to data retrieved from the database, and I believe that such action requires the use of the DOM getElementById, createElement, setAttribute and appendChild functions, which in turn requires that the page be loaded with the PHP loadHTMLFile function.

Can anyone help, please?


Thanking you,
Sofia

Re: loadHTMLFile for PHP files

Posted: Sun Feb 02, 2014 11:42 pm
by requinix
It'd be nice to see some code.

Re: loadHTMLFile for PHP files

Posted: Mon Feb 03, 2014 12:25 am
by iSofia
Hi requinix. The PHP file is essentially HTML content with some nested PHP functions to populate and validate input fields:
<input type="text" ... value="<?php echo (isset($_POST['name'])) ? $_POST['name'] : ''; ?>".

Besides these, the document is purely HTML. However, when the file is loaded with the PHP loadHTMLFile function like this:

Code: Select all

$html=$DOCUMENT_ROOT. "test.php";
$page=new DOMDocument();
$page->loadHTMLFile($html);
...get existing elements by ID
...create new elements
...append new elements to existing elements
$page->saveHTMLFile($html);
the PHP tags <?PHP ?> in the HTML code is replaced with &lt?php ?&gt, eseentially corrupting the PHP code.

Is there perhaps any other way to dynamically add content without using loadHTMLFile, and maybe another function that will load the file as PHP?

Thank you.

Re: loadHTMLFile for PHP files

Posted: Mon Feb 03, 2014 12:27 am
by requinix
DOMDocument is not going to execute PHP code contained in the HTML you're loading.

I think maybe what you're aiming for is
1. ob_start
2. include() the file
3. ob_get_clean
4. Load the HTML "outputted" into DOMDocument and continue

Re: loadHTMLFile for PHP files

Posted: Mon Feb 03, 2014 3:58 am
by iSofia
Hello again requinix. Thanks for the pointer to the ob_* functions. I looked them up, and they seem to be output buffer functions, but I don't see how I could dynamically append elements to it?

Re: loadHTMLFile for PHP files

Posted: Mon Feb 03, 2014 2:20 pm
by requinix
Output buffering (the ob_* functions) are just so that you can evaluate the PHP code contained in the HTML. Once that's done, you load the HTML into DOMDocument and continue on like you're doing now.