duanchui1955 2014-10-13 14:15
浏览 55
已采纳

PHP:无法打印DOMDocument的第一个值

I have a PHP script that is supposed to read an HTML file and then return the contents of the first <h1> tag that it finds. I do not want to use regex or the Simple HTML DOM Parser please - just plain, easy PHP.

This is my code thus far:

$document = new DOMDocument();
$document->loadHTMLFile($post_url);
$matches = $document->getElementsByTagName('h1');
$first_h1 = $matches->item(0);
echo $first_h1;

However, when I run the code, I get an error that says PHP Catchable fatal error: Object of class DOMElement could not be converted to string

Can anyone help me with where I am going wrong?

Thanks in advance!

SOLUTION: Replacing the last line with echo $first_h1->nodeValue; seems to do the trick.

  • 写回答

3条回答 默认 最新

  • dongxian7194 2014-10-13 14:18
    关注

    The issue is that $first_h1 is a DOMElement object rather than a string, and it has no method to convert itself to a string, so you cannot simply echo it out. You can, however do a var_dump on it:

    $document = new DOMDocument();
    $document->loadHTMLFile($post_url);
    $matches = $document->getElementsByTagName('h1');
    $first_h1 = $matches->item(0);
    var_dump($first_h1);
    

    If you need to get the text contents of the element (i.e. the text between the tags), use the nodeValue property:

    echo $first_h1->nodeValue;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥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 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看