您正在寻找不是仅空白节点的第一个文本节点子节点:
// xpath: text()[normalize-space(.)][1]
$thedate = $xpath->query(
'text()[normalize-space(.)][1]', $reviewdate
)->item(0);
结果(var_dump($thedate->data)
):
string(39) "\n Movie Review - Mar 24, 2013\n "
string(39) "\n Movie Review - Mar 23, 2013\n "
此外,当您正在寻找一个值时,您可能希望直接检索字符串值:
// xpath: normalize-space(text()[normalize-space(.)])
$thedate = $xpath->evaluate(
'normalize-space(text()[normalize-space(.)])', $reviewdate
);
结果(var_dump($thedate)
):
string(27) "Movie Review - Mar 24, 2013"
string(27) "Movie Review - Mar 23, 2013"
我希望这是有帮助的。另请参阅在线演示和完整的代码示例:
<?php
/**
* how can I get the text data of a div without the child divs text data - with php xpath?
*
* @link http://stackoverflow.com/q/15838487/367456
* @link http://eval.in/15474
*/
$buffer = <<<BUFFER
<html>
<div class="date">
<div class="rating">good</div>
Movie Review - Mar 24, 2013
</div>
<div class="date">
Movie Review - Mar 23, 2013
</div>
</html>
BUFFER;
$doc = new DOMDocument();
$doc->loadHTML($buffer);
$xpath = new DOMXPath($doc);
foreach ($xpath->query('/*/body/div[@class = "date"]') as $reviewdate) {
$thedate = $xpath->query('text()[normalize-space(.)][1]', $reviewdate)->item(0);
var_dump($thedate->data);
// string:
$thedate = $xpath->evaluate('normalize-space(text()[normalize-space(.)])', $reviewdate);
var_dump($thedate);
}