PHP: Can GetElementById be used in another PHP file?
I have a very complex PHP file that generates a lot of HTML, but I'm only interested in extracting only some of them (inside an element <div id="content">
) into another file. The point is that this element is generated by PHP.
Is it possible to use a PHP function getElementById
to get an item content
from another PHP file? Or even from within yourself?
For example, something like this, but actually works:
$doc = new DomDocument;
// We need to validate our document before referring to the id
$doc->validateOnParse = true;
$doc->Load('file.php');
echo "The contents are: ".$doc->getElementById('content')->textContent;
I understand this would mean that PHP has to be executed in order to generate HTML, and so the answer might just be No, this is not possible, and I also understand that this would mean a lot of extra runtime. I'm not worried about them at the moment, only if possible.
source to share
-> Download the "PHP" file, it will see the original source, which probably won't be used.
Perhaps you can use an http wrapper, functionality that activates the page over the internet. http://php.net/manual/en/wrappers.http.php
Since it is over the internet, php is executed by the web server as usual.
$doc->Load('http://your-domain.com/path/to/file.php');
But not very effective.
(there are other ways to execute the file - perhaps with shell_exec or just "include" this file after putting it into output buffering. But above is the fastest way)
source to share
This should work I think.
// init the CURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0); // we do not want to process the headers later
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // return response as a string
curl_setopt($ch, CURLOPT_URL, 'www.mywebsite.com/file.php'); // the URL
// execute the curl
// this will basically call the URL and your PHP will execute as intended
$result = curl_exec($ch);
// use loadHTML() here
$doc->loadHTML($result);
source to share
You can use $ doc - > loadHTMLFile ('file.php'); if your .php file generates some HTML in the output and uses $ elems = $ doc-> getElementById ('content');
and do foreach on the nodes;)
somes here: http://php.net/manual/fr/domdocument.loadhtmlfile.php
Edit: see call test.php test2.php
test.php
<?php
$doc = new DomDocument;
$doc->loadHTMLFile('test2.php');
$element = $doc->getElementById('tested')->textContent;
print_r($element);
?>
test2.php
<?php
echo"
<html>
<head></head>
<body>
<div id='tested'>texte ok</div>
</body>
</html>";
?>
and its work :)
source to share
what you can do is edit a complex file by adding:
ob_start()
at the top and
$contents = ob_get_clean();
at the end
Then something like:
if(isset($_GET['getLimitedContent'])){
$doc = new \DomDocument;
$doc->loadHTML($contents);
// parse out and echo the required elements
}else{
echo $contents;
}
source to share