Home > Backend Development > PHP Tutorial > PHP code example using xpath to parse html

PHP code example using xpath to parse html

不言
Release: 2023-04-05 08:08:01
forward
3687 people have browsed it

This article brings you code examples about using PHP to parse HTML using xpath. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Instance 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/>"; 
}
Copy after login

Instance 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);
}
Copy after login

The above is the detailed content of PHP code example using xpath to parse html. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template