0
<div class="date">
  <div class="rating">good</div>
  Movie Review - Mar 24, 2013
</div>

<div class="date">
  Movie Review - Mar 23, 2013
</div>

什么 xpath 查询将获得“Movie Review ..”部分而没有评级 div 内容(它说好)。有时评级 div 有时不存在。

当我得到一个 div 节点时,我尝试了这种事情$reviewnode:

  $thedate = $xpath->query('text()[1]',$reviewdate)->item(0) ;

但它也捕获了评级 div 的内容。

解析后的文档是 html5。

4

2 回答 2

1

这应该返回包含字符串“Movie”的 div 的文本子项:

//div[@class = "date"]/text()[contains(., "Movie")]

如果您只想要第一个非空白文本节点,您可以使用

//div[@class = "date"]/text()[normalize-space(.) != ''][1]
于 2013-04-05T16:13:41.537 回答
0

您正在寻找不是仅空白节点的第一个文本节点子节点:

// 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);
}
于 2013-04-08T11:41:17.880 回答