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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历