dtz8044 2014-03-11 13:46
浏览 34
已采纳

使用Simple HTML Dom PHP

Ok i have a bit of a problem and hope someone can help me out.

I'm using Simple HTML Dom PHP Class and trying to grab info from another site example below.

$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 = '';
}

Now on the site where this code gets the info from there are two that are the same example below

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

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

Now i only want to grab the Country but some times the Country is not available and it ends up getting the run time so could i use

<h3>Country:</h3>

Part to stop this could someone please help me out thanks.

  • 写回答

1条回答 默认 最新

  • dr5779 2014-03-12 11:08
    关注

    The setup:

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

    Using simple you need to jump through some hoops

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

    Using advanced you can get there with css:

    $country = $doc->find('h3[text="Country:"] + span', 0)->text();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?