Object of class DOMNodeList could not be converted to string

21,969

Yeah, DOMXpath::query returns are always a DOMNodeList, which is a bit of an odd object to deal with. You basically have to iterate over it, or just use item() to get a single item:

// There's actually something in the list
if($result->length > 0) {
  $node = $result->item(0);
  echo "{$node->nodeName} - {$node->nodeValue}";
} 
else {
  // empty result set
}

Or you can loop through the values:

foreach($result as $node) {
  echo "{$node->nodeName} - {$node->nodeValue}";
  // or you can just print out the the XML:
  // $dom->saveXML($node);
}
Share:
21,969
Ryan
Author by

Ryan

Updated on July 09, 2022

Comments

  • Ryan
    Ryan almost 2 years

    I got the above error and tried to print out the object to see how I could access the data inside of it but it only echoed DOMNodeList Object ( )

    function dom() {
    $url = "http://website.com/demo/try.html";
    $contents = wp_remote_fopen($url);
    
    $dom = new DOMDocument();
    @$dom->loadHTML($contents);
    $xpath = new DOMXPath($dom);
    
    $result = $xpath->evaluate('/html/body/table[0]');
    print_r($result);
        }
    

    I'm using Wordpress, thus explains the wp_remote_fopen function. I'm trying to echo the first table from $url

  • Ryan
    Ryan about 13 years
    Thanks, that really helped my understanding!