如何在XPath查询中启动第二个和第三个XPath查询? 例如
CodePad = http://codepad.viper-7.com/ZhMNGw
HTML CODE
<div class="entries">
<h3 class="headline" style="position: relative; cursor: pointer;">
<div>
<a class="selink" href="/tste/?sd=28726585">
<span class="date"> 10:15 </span>
<span class="titel">THE TITLE<span class="subtitel">some subtitle</span>
</span>
</a>
</div>
</h3>
</div>
<div class="entries">
<h3 class="headline" style="position: relative; cursor: pointer;">
<div>
<a class="selink" href="/tste/?sd=287265995">
<span class="date"> 10:16 </span>
<span class="titel">THE TITLE 2<span class="subtitel">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);
答案 0 :(得分:1)
$ xpath-&gt;查询($ expr)在循环内的每个调用中对整个文档执行,因为您没有通过文档节点,XPath查询应该相对评估。
使用多态方法DOMNodeList query(string $expr, DOMNode $node),您可以执行相对于给定$节点的子查询。 仅当您使用相对XPath $ expr(不带前导/)时,此方法才会生成所需结果。 要从每个DOMNode / TextNode检索字符串,最后使用以下查询:
$list[$count]['url'] = $xpath->query("h3/div/a[@class='selink']/@href", $value)->item(0)->value;
$list[$count]['title'] = $xpath->query("h3/div/a/span[@class='titel']/text()", $value)->item(0)->wholeText;
我编辑了您的CodePad代码here。
的问候, 最大