In PHP using DomDocument getElementByID does not work? What am I doing wrong?

Here is some 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 a few specific identifiers from a website, it just shows one, and I saw this method everywhere, including here, but when I try to print something, nothing appears. I tried testing to see that he was reading something using

 if(!$tryID) { ("Element not found"); } 

But he never prints. Finally, I used

 echo $tryID->nodeValue; 

and still nothing ... does anyone know what i am doing wrong?

Also, if I get this working, can I read several different things for different variables in the same $ dom? If that makes sense.

+4
source share
1 answer

So, your decision.

For 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 a file while you are transmitting well-designed XML or XHTML content by modifying

 $dom->loadHTMLFile('YourFile.html'); 

to

 $dom->loadHTML($html); 

Oh yes, and of course, CHANGE the contents (for completeness):

 $div->removeChild($div->firstChild); $newText = new DOMText('Yes this works!'); $div->appendChild($newText); 

Then you can simply repeat it or something else.

+3
source

Source: https://habr.com/ru/post/1444239/


All Articles