PHP DOM getElementsbytagname()getElementById()

I'm working in PHP and looking at the DOM to parse html and find certain information on the page.

I have code working well using the getElementsbyTagName():

foreach ($dom->getElementsByTagName('div') as $node) {
          $array_data[ ] = $node->nodeValue;
        }

print_r($array_data);

On the page I'm looking at there are a lot of <div>'s. The div i'm interested in has a unique id on the page. I thought I could select this specific information By updating my code to look at the id as below:

foreach ($dom->getElementById('tree___34LHOENOP7') as $node) {
          $array_data[ ] = $node->nodeValue;
        }

print_r($array_data);

This code does not seem to work. The html:

<div id="tree___34LHOENOP7" style="margin-top: 5px; font-family: Verdana, Arial, sans-serif; height: 528px; overflow: auto;">
<ul><li style="list-style-type:none;"><span style="cursor:pointer;color:#D99F00;" onclick="prtv_C_E(this,'ExpandableRegionClickHandler','',2,true);(2,this);">UK</span><img src="https://images... " title="re-centre map here" onclick="ExpandableRegionClickHandler(2,this);" style="display:inline;margin-left:7px;cursor:pointer;"><ul style="display:block;"><li style="list-style-type:none;"><span style="cursor:pointer;color:#D99F00;" onclick="prtv_C_E(this,'ExpandableRegionClickHandler','',59,true);ExpandableRegionClickHandler(59,this);">Channel Islands</span><img src="https://images... " title="re-centre map here" onclick="ExpandableRegionClickHandler(59,this);" style="display:none;margin-left:7px;cursor:pointer;"><ul style="display:none;"><li style="list-style-image:url('http://images…’);"><a class="MapEventName" href="http://www... /guernsey" onclick="EventSpanClick(1439,this);" onmouseover="EventSpanMouseOver(1439,this);" onmouseout="EventSpanMouseOut(1439,this);">Guernsey</a></li>

Hope this will help you out, DOMDocument::getElementById will return DOMElement Object.

$domObject= new DOMDocument();
$domObject->loadHTML($source);//put your complete source html string here
$result=$domObject->getElementById("tree___34LHOENOP7");//this will output DOMElement Object
print_r($result->nodeValue);

Documentation explain well:

getElementbyId:

Returns a reference to the element by its ID; the ID is a string which can be used to uniquely identify the element, found in the HTML id attribute

getElementsByTagName:

The Element.getElementsByTagName() method returns a live HTMLCollection of elements with the given tag name.

You don't need to use foreach with getElementById, because you get only one element.

Look at the names getElementsByTagName has the plural elements but getElementById has the singular element.

When you use getElementsByTagName you have to loop over the result.

When you use getElementById there is nothing to loop over. You get a single result. Remove the loop.

$node = $dom->getElementById('tree___34LHOENOP7');
$array_data[ ] = $node->nodeValue;
print_r($array_data);