删除PHP XML DOM中的匹配节点

时间:2014-12-13 22:49:21

标签: php xml dom

$content_properties包含xpath查询的结果:<td>包含一些简单的文本值。我想删除值等于&#34;最后查看&#34;的每个节点。所以我尝试了这个:

<?php
    foreach($content_properties as $node){
        if($node->nodeValue == "last viewed"){
            $node->parentNode->removeChild($node);
            echo "yep - ".$node->nodeValue."<br>";
        }
        else{
            echo "nope - ".$node->nodeValue."<br>";
        }
    }
?>

但是当我再次回显所有$ content_properties节点值时,没有删除任何内容。

  • 我没有收到警告或错误。
  • 我添加了yep / nope回声以检查表达式是否实际匹配正确的节点。它是。
  • 我尝试更改匹配节点的值,只是为了查看它是否有效。它确实。

为什么我无法移除匹配的节点?我是否必须做其他事情才能删除&#39;?我不是以正确的节点为目标吗?

2 个答案:

答案 0 :(得分:1)

您正在做的工作正常,节点已从其父节点中移除 - 它们不会从DOMNodeList $content_properties移除。


实施例

$xml = <<<'XML'
<tr>
    <td>foo</td>
    <td>bar</td>
    <td>last viewed</td>
    <td>baz</td>
    <td>last viewed</td>
</tr>
XML;

$dom = new DOMDocument();
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);

$content_properties = $xpath->query('//td');

foreach($content_properties as $node){
    if($node->nodeValue == "last viewed"){
        $node->parentNode->removeChild($node);
    }
}

foreach($content_properties as $node){
    if($node->nodeValue == "last viewed"){
        echo "yep - ".$node->nodeValue."\n";
    }
    else{
        echo "nope - ".$node->nodeValue."\n";
    }
}

echo "\n", $dom->saveXML(), "\n";

// Regen the DOMNodeList
$content_properties = $xpath->query('//td');

foreach($content_properties as $node){
    if($node->nodeValue == "last viewed"){
        echo "yep - ".$node->nodeValue."\n";
    }
    else{
        echo "nope - ".$node->nodeValue."\n";
    }
}

输出:

nope - foo
nope - bar
yep - last viewed
nope - baz
yep - last viewed

<?xml version="1.0"?>
<tr>
    <td>foo</td>
    <td>bar</td>

    <td>baz</td>

</tr>

nope - foo
nope - bar
nope - baz

答案 1 :(得分:0)

这是正确的方法:

<?php
    foreach($content_properties as $node){
        if($node->nodeValue == "last viewed"){
            $content_properties->parentNode->removeChild($node);
            echo "yep - ".$node->nodeValue."<br>";
        }
        else{
            echo "nope - ".$node->nodeValue."<br>";
        }
    }
?>