The goal is to extract an element from a locally stored html file and insert it into the current page at the point when the php script is executed. This has been my first major PHP project so I expect the issue is simple (and I apologise for any non-technical language), but, as you will see, I cannot resolve it.
My code looks like this:
<?php
$path = $_SERVER["DOCUMENT_ROOT"]."/bglibrary/background.html";
$html = new DOMDocument();
$html->loadHtmlFile($path);
$xpath = new DOMXPath ( $html );
$background = $xpath->query("//*[@id='background-wrapper']");
var_dump($background); // object(DOMNodeList)#307 (0) { }
var_dump($background->item(0)); // object(DOMElement)#306 (0) { }
var_dump($background->item(1)); // NULL
var_dump($html->saveHTML($background)); // NULL
var_dump($html->saveHTML($background->item(0))); // NULL
echo $html->saveHTML(); //Prints full html of the target page
?>
The var_dump commands are to debug, and they illustrate the problem. The x-path query is succeeding I think, because it returns a list of nodes with one item only (querying the second item on the list returns NULL). Furthermore, the item itself is identified as a dom element.
However I have not been able to use saveHTML in any form (including finding the target node's parent and then finding the element inside it to try and save it), or saveXML, or saveHTMLfile, to return, echo, print or dump the desired element. I have also tried using the getElementById php function with the exact same results.
In case it's a factor, my html (which is very simple also) follows;
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Holding File for Images</title>
<style type="text/css">
... some styling
</style>
</head>
<body>
<div id="background-wrapper">
<div id="background1" dataalt="no" class="background">
...A whole load of div elements
</div>
<div id="background2" class="background">
...A whole load of div elements
</div>
</div>
</body>
</html>
And finally, just in case you were thinking that the html file isn't being accessed properly somehow, that final echo $html->saveHTML(); from my php does successfully output the entire html file I just listed, and it renders nicely.
An extremely similar question was asked this year by remyable and received no answer apart from that the code seemed to run ok according to another user. I can assure you, this code and no similar variation seems to run ok, therefore I suspect the issue may lie in my server setup. I'm executing the PHP inside the header.php file of a wordpress site, which is hosted locally using MAMP to run. The MAMP server root is not the 'wordpress' file (since I'm working on some non-wordpress stuff too), hence why I use the DOCUMENT_ROOT command to find my html file. The file paths relevant to this case are:
root/wordpress/wp-content/themes/FirstTheme/header.php (where the php is being executed)
root/bglibrary/background.html (where the target HTML file is)