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 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了