使用类名解析curl结果

时间:2013-08-02 09:05:06

标签: php curl html-parsing domdocument

我正在使用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";   
}
}
?>

1 个答案:

答案 0 :(得分:2)

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