从XML搜索特定节点值

时间:2014-12-29 05:42:24

标签: php xml xpath domdocument

这是我的PHP / XML代码。我只是想从这个搜索特定的$searchterm

$doc = new DOMDocument;
$doc->load('authentication.xml');

$xpath = new DOMXPath($doc);

$searchTerm = "N0A097016646";

$lineNo = 0;
foreach ($xpath->query('//device/following::comment()') as $comment){
    $serial= $xpath->query('//device', $comment)->item($lineNo)->textContent;

    echo "Line number: ".$comment->getLineNo()." Device number: ".$serial." Comented number: ".$comment->textContent."<br>";

    $lineNo++;
}

我应该在哪里放$searchTerm变量来搜索该特定节点?

1 个答案:

答案 0 :(得分:1)

如您的问题所示,您无法使用$searchTerm

=(等于)

一起使用
text() = '$searchTerm'

代码:

$searchTerm = "N0A097016646";

foreach ($xpath->query("//device[text() = '$searchTerm']/following::comment()") as $comment){
    echo "Line number: ".$comment->getLineNo(). '<br/>'.
    " Device number: ".$searchTerm.'<br/>'.
    " Comented number: ". $comment->textContent."<hr>";
}

Sample Output