An object of class DOMNodeList cannot be converted to a string

I got the above error and tried to print the object to see how I can access the data inside it, but it only repeated the 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 use Wordpress, therefore explains the wp_remote_fopen function. I am trying to repeat the first table from $ url

+3
source share
2 answers

Yes, it DOMXpath::queryalways returns DOMNodeList, which is a slightly strange object to deal with. You basically need to iterate over it or just use it item()to get one element:

// There 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 scroll through the values:

foreach($result as $node) {
  echo "{$node->nodeName} - {$node->nodeValue}";
  // or you can just print out the the XML:
  // $dom->saveXML($node);
}
+13
source

Xpath starts the index using 1 not 0: /html/body/table[1]

, HTML- node node.

$html = <<<'HTML'
<html>
  <body>
    <p>Hello World</p>
  </body>
</html>
HTML;

$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);

// iterate all matched nodes and save them as HTML to a buffer
$result = '';
foreach ($xpath->evaluate('/html/body/p[1]') as $p) {
  $result .= $dom->saveHtml($p);
}
var_dump($result);

// cast the first matched node to a string
var_dump(
  $xpath->evaluate('string(/html/body/p[1])')
);

: https://eval.in/155592

string(18) "<p>Hello World</p>"
string(11) "Hello World"
0

All Articles