Using PHP to Get DOM Element
Manipulating HTML within PHP requires a firm grasp of how DOMDocument and the DOMElement class interact, particularly when parsing dynamic or non-standard markup. The core issue in your original code stems from a fundamental misunderstanding of what DOMDocument::load() expects versus what you are providing, combined with an inefficient iteration pattern that prevents you from targeting specific elements.
When you call $dom->loadHTML("index.php"), you are instructing the DOM parser to read the raw file at that path and construct a document tree from it. However, your subsequent code attempts to iterate over every element and then every attribute on those elements. This approach is both computationally expensive and logically flawed for your goal of finding a specific ID. If you need to extract a custom attribute like srckey from an element with the ID currentLocation, iterating through all nodes is unnecessary overhead.
The primary error in your snippetâWarning: DOMDocument::load() ... Extra content at the end of the documentâoccurs because DOMDocument::load() expects a complete, well-formed XML or HTML5 document. If you pass it a file path that returns PHP code containing multiple <div> blocks (as implied by your structure), the parser sees the closing tag of the first block and then encounters subsequent content, interpreting it as "extra content" outside the root element. To fix this, you must ensure the string passed to load() or loadHTML() is either a complete document fragment wrapped in a single root node, or you use methods designed for parsing strings that might not be perfectly valid standalone documents.
A more robust approach is to load the external file content into memory as a string first, then parse it. This allows you to control exactly what enters the DOM tree. Once the document is loaded, you should bypass the generic getElementsByTagName loop entirely. Instead, use $dom->getElementById('currentLocation'). This method directly targets the specific node you care about, returning a DOMElement object or null if the ID does not exist.
Once you have the specific element, accessing your custom attribute is straightforward using getAttribute(). However, there is a critical detail regarding non-standard attributes. The DOM standard only recognizes lowercase attribute names. If your PHP output generates <div id="currentLocation"> but your JavaScript sets srckey, ensure the case matches exactly when calling getAttribute('srckey'). If the attribute name contains spaces or invalid characters, you must use attributes->getNamedItem() instead of getAttribute().
Here is how you should restructure your logic to avoid the "non-object" fatal error and the parsing warnings:
// Load the external file content as a string
$filename = $_SERVER["DOCUMENT_ROOT"] . "/index.php";
$content = file_get_contents($filename);
if ($content === false) {
die("Failed to read index.php");
}
// Create the DOM document and load the string
$dom = new DOMDocument();
// Suppress warnings for malformed HTML if necessary, or ensure content is valid
libxml_use_internal_errors(true);
$dom->loadHTML($content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
libxml_clear_errors();
// Target the specific element directly
$currentLocation = $dom->getElementById('currentLocation');
if ($currentLocation !== null) {
// Access the standard attribute
$idValue = $currentLocation->getAttribute('id');
// Access the non-standard attribute
$srckey = $currentLocation->getAttribute('srckey');
// Output safely, ensuring we don't print HTML tags as text if not intended
echo "ID: {$idValue}";
echo "Source Key: {$srckey}";
} else {
echo "Element with ID 'currentLocation' not found.";
}
By loading the file content explicitly and using getElementById, you eliminate the iteration overhead and avoid the parsing errors caused by multiple root-level elements. This pattern ensures that even if your HTML structure is slightly malformed, the DOM parser can handle it gracefully provided you manage the internal error reporting correctly. If you are building a larger application where handling such dynamic content is frequent, consider migrating to Laravel's built-in helpers or using an XML/XSLT processor for more complex transformations, as manual DOM manipulation can become brittle quickly.