用php xpath获取节点文本时遇到麻烦

时间:2013-03-05 21:25:32

标签: php xpath

我有以下html:

<div class="data">
    <p class="info">output</p>
     <p class="info">output2</p>

我正在尝试使用以下

获取文本“output”
$xpath = new DOMXPath($dom);    

foreach ($xpath->evaluate("//div[@class='data']/p[1]") as $elt) {
    $output=$elt->wholeText;
}

echo $output;

它不起作用。我收到2个错误:

Message: Undefined property: DOMElement::$wholeText
Message: Undefined variable: output

有人能指出我正确的方向吗?

提前致谢,

比尔

1 个答案:

答案 0 :(得分:1)

试试这个:

$xpath = new DOMXPath($dom); 

$elements = $xpath->query("*/div[@class='data']");

if (!is_null($elements)) {
  foreach ($elements as $element) {
    $nodes = $element->childNodes;
    foreach ($nodes as $node) {
      echo $node->nodeValue. "\n";
    }
  }
}