【问题标题】:Using Simple HTML Dom PHP使用简单的 HTML Dom PHP
【发布时间】:2014-03-12 19:08:25
【问题描述】:

好的,我有一点问题,希望有人可以帮助我。

我正在使用简单的 HTML Dom PHP 类并尝试从下面的另一个站点示例中获取信息。

$html = file_get_html("http://example.com");
$find_country = $html->find('div[class=inline] span', 0);
if (!empty($find_country)) {
    $country = $find_country->plaintext;
} else {
    $country = '';
}

现在在此代码从中获取信息的网站上,有两个与下面的示例相同

<div class="inline">
    <h3>Country:</h3>
    <span>USA</span>
</div>

<div class="inline">
    <h3>Run Time:</h3>
    <span>120 min</span>
</div>

现在我只想获取国家,但有时国家不可用,它最终获得运行时间,所以我可以使用

<h3>Country:</h3>

部分阻止这件事,请有人帮我谢谢。

【问题讨论】:

    标签: php html dom


    【解决方案1】:

    设置:

    $html = <<<EOF
    <div class="inline">
        <h3>Run Time:</h3>
        <span>120 min</span>
    </div>
    
    <div class="inline">
        <h3>Country:</h3>
        <span>USA</span>
    </div>
    EOF;
    
    $doc = str_get_html($html);
    

    使用简单你需要跳过一些障碍

    foreach($doc->find('h3') as $h3){
      if($h3->text() == 'Country:'){
        $country = $h3->next_sibling()->text();
        break;
      }
    }
    

    使用 advanced 你可以通过 css 到达那里:

    $country = $doc->find('h3[text="Country:"] + span', 0)->text();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多