2013-08-02 37 views
2

我正在使用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

一個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); 
} 
+0

謝謝,它只顯示文本,超鏈接丟失。我可以用html獲得結果嗎? –

+0

看我的編輯,你可以使用'$ dom-> saveXML($ div)'獲取HTML。 – MrCode

+0

謝謝,它正在工作。 –