Explanation of code example of php parsing html with xpath

  • 2021-11-24 01:07:53
  • OfStack

Example 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/>"; 
}

Example 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);
}

The above is related to the 2 instances of content, as well as related code, thank you for the support of this site.


Related articles: