绵阳动力网站建设

php+xpath解析html页面代码的两个简单方法

时间:2019-02-18

有网站开发过程中,有时我们需要对一个html的代码来解析,网上的方法很多,但都相对比较复杂,今天绵阳动力网站建设来为大家介绍两个比较简单的方法。首先,让我们先了解一下,什么是XPath。XPath即为XML路径语言(XML Path Language),它是一种用来确定XML文档中某部分位置的语言。那如何结合PHP来解析html页面呢?方法如下:

方法一:

$xml = simplexml_load_file('http://www.webmy.cn'); 
 
$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/>"; 
}

方法二:

$url = 'http://www.webmy.cn';
$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);
}

好了,以上两个方法都可以实现解析html页面代码的功能,你可以根据自己的网站建设需求来选择。

Copyright © 绵阳动力网站建设 www.kf51.cn All Rights Reserved 蜀ICP备08100083号

客服微信
客服微信
0816-6339181
客服微信
my_dongli