In PHP, using DomDocument getElementByID not working? What am I doing wrong?

Michael Staudt picture Michael Staudt · Nov 6, 2012 · Viewed 9.5k times · Source

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.

Answer

Fernando Cordeiro picture Fernando Cordeiro · Nov 6, 2012

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.