Here is a bit of my code...
$dom = new DomDocument;
$html = $newIDs[0];
$dom->validateOnParse = true;
$dom->loadHTML($html);
$dom->preserveWhiteSpace = true;
$tryID = $dom->getElementById('ID');
echo $tryID;
I am trying to get multiple specific IDs from a website, this just shows one, and I have seen this method everywhere, including on here, but when I try and print something out nothing shows up. I tried testing to see if it is reading something in with
if(!$tryID)
{
("Element not found");
}
But it never prints that out either. Lastly, I have used
echo $tryID->nodeValue;
and still nothing... anyone know what I am doing wrong?
Also, if I do get this working can I read in multiple different things to different variables on the same $dom ? If that makes ay sense.
The DOMDocument::getElementById() function is an inbuilt function in PHP which is used to search for an element with a certain id. Parameters:This function accepts a single parameter $elementId which holds the id to search for. Return Value: This function returns the DOMElement or NULL if the element is not found.
The getElementById() method returns null if the element does not exist.
The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.
Dom parser travels based on tree based and before access the data, it will load the data into dom object and it will update the data to the web browser. Below Example shows how to get access to the HTML data in web browser. <? $cols->item(0)->nodeValue.
Ok, so your solution.
For a DIV:
<div id="divID" name="notWorking">This is not working!</div>
This will do:
<?php
$dom = new DOMDocument("1.0", "utf-8");
$dom->loadHTMLFile('YourFile.html');
$div = $dom->getElementById('divID');
echo $div->textContent;
$div->setAttribute("name", "yesItWorks");
?>
Should work without the file as long as you pass a Well-Made XML or XHTML content, changing
$dom->loadHTMLFile('YourFile.html');
to your
$dom->loadHTML($html);
Oh yeah, and of course, to CHANGE the content (For completeness):
$div->removeChild($div->firstChild);
$newText = new DOMText('Yes this works!');
$div->appendChild($newText);
Then you can just Echo it again or something.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With