首頁  >  文章  >  後端開發  >  php利用xpath解析html的程式碼範例

php利用xpath解析html的程式碼範例

不言
不言轉載
2019-02-14 13:57:153617瀏覽

這篇文章帶給大家的內容是關於php利用xpath解析html的程式碼範例,有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。

實例1

$xml = simplexml_load_file('https://forums.eveonline.com'); 

$names = $xml->xpath("html/body/p/p/form/p/p/p/p/p[*]/p/p/table//tr/td[@class='topicViews']"); 
foreach($names as $name) 
{ 
    echo $name . "<br/>"; 
}

實例2

$url = &#39;http://www.baidu.com&#39;;
$ch = curl_init();
curl_setopt($ch, CURLOPT_FILE, fopen(&#39;php://stdout&#39;, &#39;w&#39;));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL, $url);
$html = curl_exec($ch); 
curl_close($ch);

// create document object model
$dom = new DOMDocument();
// load html into document object model
@$dom->loadHTML($html);
// create domxpath instance
$xPath = new DOMXPath($dom);
// get all elements with a particular id and then loop through and print the href attribute
$elements = $xPath->query(&#39;//*[@id="lg"]/img/@src&#39;);
foreach ($elements as $e) {
  echo ($e->nodeValue);
}

以上是php利用xpath解析html的程式碼範例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:csdn.net。如有侵權,請聯絡admin@php.cn刪除