简单的html dom抓住h1标头

时间:2016-08-11 12:39:20

标签: php html dom simple-html-dom

我刚刚学习了simple_html_dom.php, 我尝试用某个类来获取h1内容。

<h1 class="entry-title">example for the header</h1>

这里是我想要获取内容的网站上的原始html文件。

    <header class="entry-header">
    <div class="entry-meta">
        <span class="cat-links"><a href="https://xxxxx/2016/08/11/xxxxxxx" rel="category tag">News</a></span>
    </div>
    <h1 class="entry-title">example for the header</h1>
    <div class="entry-meta">
        <span class="entry-date"><a href="https://xxxxx/2016/08/11/xxxxxxx" rel="bookmark"><time class="entry-date" datetime="2016-08-11T11:54:07+00:00">11 August 2016</time></a></span> 
        <span class="byline"><span class="author vcard"><a class="url fn n" href="https://xxxxx/2016/08/11/xxxxxxx" rel="author">wndwnrt</a></span></span>          
        <span class="comments-link"><a href="https://xxxxx/2016/08/11/xxxxxxx">1 Comment</a></span>
    </div>
</header>

这里我的代码是获取h1 class =“entry-title”内容(标题的示例)

<?php
 require_once __DIR__.'/simple_html_dom.php';
 $html = new simple_html_dom();
 $html->load_file('https://xxxxx/2016/08/11/xxxxxxx');
 $header_1 = $html->find('h1[class="entry-title"]')->innertext;
?>
<table border="1">
 <thead>
   <tr>
     <th><?php echo $header_1; ?></th>
  </tr>
 </thead>
</table>

当我运行代码时,结果是错误:

Trying to get property of non-object

任何人都可以告诉错误在哪里?我该怎么办? 非常感谢你。

1 个答案:

答案 0 :(得分:5)

是的,您看到了该错误,因为您只向查找函数传递了一个参数。

$header_1 = $html->find('h1[class="entry-title"]')->innertext

现在试试这个:

$header_1 = $html->find('h1[class="entry-title"]',0)->innertext

因为您还必须传递您想要获得的h1的数量!