user3522725
user3522725

Reputation: 397

Loop through two DOMNodeLists at once using DOMDocument class

I got an error saying

Object of class DOMNodeList could not be converted to string on line

This is the line which contains the error:

$output .= '<li><a target="_blank" href="' . $postURL . '">' . 
$title->nodeValue . '</a></li>';

DOM

My code:

$postTitle = $xpath->query("//tr/td[@class='row1'][3]//span[1]/text()");
$postURL = $xpath->query("//tr/td[@class='row1'][3]//a/@href");

$output = '<ul>';

foreach ($postTitle as $title) {

        $output .= '<li><a target="_blank" href="' . $postURL . '">' . $title->nodeValue . '</a></li>';

}

$output .= '</ul>';

echo $output;

How can I resolve the error?

Upvotes: 0

Views: 184

Answers (1)

ThW
ThW

Reputation: 19492

You're fetching two independent node list from the DOM, iterate the first and try to use the second one inside the loop as a string. A DOMNodeList can not be cast to string (in PHP) so you get an error. Node lists can be cast to string in Xpath however.

You need to iterate the location path that is the same for booth list (//tr/td[@class='row1'][3]) and get the $title and $url inside the loop for each of the td elements.

$posts = $xpath->evaluate("//tr/td[@class='row1'][3]");

$output = '<ul>';
foreach ($posts as $post) {
  $title = $xpath->evaluate("string(.//span[1])", $post);
  $url = $xpath->evaluate("string(.//a/@href)", $post);
  $output .= sprintf(
    '<li><a target="_blank" href="%s">%s</a></li>',
    htmlspecialchars($url),
    htmlspecialchars($title)
  );
}
$output .= '</ul>';

echo $output;

Upvotes: 1

Related Questions