Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object of class DOMNodeList could not be converted to string

Tags:

dom

xpath

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

like image 750
Ryan Avatar asked May 26 '11 17:05

Ryan


1 Answers

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);
}
like image 120
onteria_ Avatar answered Jan 02 '23 19:01

onteria_



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!