欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php利用xpath解析html的代码示例

程序员文章站 2022-04-15 21:52:29
...

本篇文章给大家带来的内容是关于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 = 'http://www.baidu.com';
$ch = curl_init();
curl_setopt($ch, CURLOPT_FILE, fopen('php://stdout', 'w'));
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('//*[@id="lg"]/img/@src');
foreach ($elements as $e) {
  echo ($e->nodeValue);
}

以上就是php利用xpath解析html的代码示例的详细内容,更多请关注其它相关文章!

相关标签: php