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

php用xpath解析html的代码实例讲解

程序员文章站 2023-11-09 12:46:04
实例1 $xml = simplexml_load_file('https://forums.eveonline.com'); $names = $xm...

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

以上就是相关的2个实例内容,以及相关的代码, 感谢大家对的支持。