xpath

<?php
$url = 'http://www.nipic.com/show/15984788.html';
$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="J_detailMain"]/div[1]/h1');
var_dump($elements);
foreach ($elements as $e) {
  echo ($e->nodeValue);
}

  

原文地址:https://www.cnblogs.com/brady-wang/p/6149398.html