douan5151 2014-05-22 08:08
浏览 31

使用DOMDocument类一次循环两个DOMNodeLists

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?

  • 写回答

1条回答 默认 最新

  • dongshi6710 2014-05-22 13:38
    关注

    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;
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看