简单的HTML dom抓取h1标题


simple html dom grabbing h1 header

我刚刚学习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

谁能告诉错误在哪里?我该怎么做呢?非常感谢。

可以看到错误,因为您只向find函数传递了一个参数。

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

现在试试这个:

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

,因为您还必须传递您试图获得的h1的编号!