Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 884
Michael Staudt Avatar asked Nov 06 '12 02:11

Michael Staudt


People also ask

Does document getElementById work in PHP?

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.

What does getElementById return if not found?

The getElementById() method returns null if the element does not exist.

What does document getElementById() do?

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.

How to use dom in PHP?

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.


1 Answers

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.

like image 172
Fernando Cordeiro Avatar answered Oct 16 '22 10:10

Fernando Cordeiro