使用简单的HTML Dom PHP


Using Simple HTML Dom PHP

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

我正在使用简单的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>

部分停止这个,谁能帮帮我,谢谢。

设置:

$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);

使用simple你需要跳过一些障碍

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();