【问题标题】:parse the curl result using class name使用类名解析 curl 结果
【发布时间】:2013-08-02 09:05:06
【问题描述】:

我正在使用 curl 功能从另一端获取信息,但它显示的是网站的完整页面。我想根据班级名称显示内容。请让我知道我该怎么做? 我正在使用以下代码:-

 <?php
 $curl = curl_init('http://www.insolvency.govt.nz/cms/search?SearchableText=smith');
 curl_setopt($curl, CURLOPT_FAILONERROR, true);
 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);  
 $result = curl_exec($curl);
 $dom = new DOMDocument();
 $res=$dom->loadHTML($result);
 $divs = $dom->getElementsByTagName('div');

 foreach($divs as $div) {
 if ($div->getAttribute('id') === 'searchResult') {
     echo $div->nodeValue;
 }else{
echo "error";   
}
}
?>

【问题讨论】:

    标签: php curl html-parsing domdocument


    【解决方案1】:

    XPath 可用于按类名获取元素。下面的示例将获取具有myClass 类的元素。

    $dom = new DOMDocument();
    $res=$dom->loadHTML($result);
    
    $xpath = new DomXPath($dom);
    $class = 'myClass';
    $divs = $xpath->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $class ')]");
    
    foreach($divs as $div) {
        echo $div->nodeValue;
    
        echo $dom->saveXML($div);
    }
    

    【讨论】:

    • 谢谢,它只显示文本,缺少超链接。我可以用 html 得到结果吗?
    • 查看我的编辑,您可以使用$dom-&gt;saveXML($div) 获取HTML。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-07
    • 2017-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多