有网站开发过程中,有时我们需要对一个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页面代码的功能,你可以根据自己的网站建设需求来选择。
地址:绵阳市临园路东段78号B座13层
电话:0816-6339181
邮箱:kf@kf51.cn
微信公众号:
Copyright © 绵阳动力网站建设 www.kf51.cn All Rights Reserved 蜀ICP备08100083号