Search code examples
phpxml-parsingdomdocument

DOMDocument getElementsByTagName not working


I'm trying to use the DOMDocument function getElementsByTagName(), but it keeps returning an empty object. I'm using the following code:

// Create some HTML
$output = '
<html>
   <body>
      <a href="foo">Bar</a>
   </body>
</html>';

// Load the HTML
$dom = new DOMDocument;
$dom->loadHTML($output);

// Find all links (a tags)
$links = $dom->getElementsByTagName('a');

var_dump($links); // object(DOMNodeList)#31 (0) { } - empty object

What am I missing? Looking at the documentation, it looks like I'm using the function correctly.


Solution

  • That var_dump is just saying that you have a DOMNodeList object. Traverse the list and you'll see it's there:

    foreach( $links as $a) {
         echo $a->nodeName . ' ' . $a->nodeValue;
    }
    

    This would output:

    a Bar 
    

    Since it's an <a> tag, and its contents are Bar.