php - XPath query in an XPath query
800
how can a start a second and third XPatch query in an XPatch query?
For example
CodePad = http://codepad.viper-7.com/ZhMNGw
HTML CODE
<div >
<h3 >
<div>
<a href="/tste/?sd=28726585">
<span > 10:15 </span>
<span >THE TITLE<span >some subtitle</span>
</span>
</a>
</div>
</h3>
</div>
<div >
<h3 >
<div>
<a href="/tste/?sd=287265995">
<span > 10:16 </span>
<span >THE TITLE 2<span >some subtitle</span>
</span>
</a>
</div>
</h3>
</div>
PHP
libxml_use_internal_errors(true);
$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;
$doc->strictErrorChecking = false;
$doc->recover = true;
$doc->loadHTMLFile('http://domain.com/startpage.php');
$xpath = new DOMXPath($doc);
$query = "//div[@class='entries']"; // <- QUERY ONE
$entries = $xpath->query($query);
$list = array();
$count = 0;
foreach ($entries as $key => $value)
{
$list[$count] = array();
// get the link <- QUERY TWO
$list[$count]['url'] = $xpath->query("//a[@class='selink']");
// get the title but NOT the subtitle <- QUERY THREE
$list[$count]['title'] = $xpath->query("//span[@class='titel']");
$count++;
}
print_r($list);
Answer
Solution:
$xpath->query($expr) is executed on the whole document each call within the loop because you don't pass the document node the XPath query should be evaluated in relatively.
With the polymorphic method DOMNodeList query(string $expr, DOMNode $node) you can do a sub query relative to the given $node. This method produces the desired result only if you use a relative XPath $expr (without leading /). To retrieve the string from each DOMNode/TextNode finally use the queries as follows:
I edited your CodePad code here.
regards, Max