简体   繁体   English

如何使用PHP XML Dom中的属性值删除特定节点?

[英]How do I remove a specific node using its attribute value in PHP XML Dom?

My question is best phrase as: Remove a child with a specific attribute, in SimpleXML for PHP 我的问题是最好的短语: 在PHP的SimpleXML中,删除具有特定属性的孩子

except I'm not using simpleXML. 除了我不使用simpleXML。

I'm new to XML for PHP so I may not be doing the best way 我刚接触XML for PHP,所以我可能并没有采取最佳方法

I have a xml created using the $dom->save($xml) for each individual user. 我为每个用户使用$ dom-> save($ xml)创建了一个xml。 (not placing all in one xml due to undisclosed reasons) (由于未公开的原因,未将所有内容都放在一个xml中)

It gives me that xml declaration <?xml version="1.0"?> (no idea how to make it to others, but that's not the point, hopefully) 它给了我xml声明<?xml version="1.0"?> (不知道如何将其声明给其他人,但希望不是重点)

<?xml version="1.0"?>
<details>
 <person>name</person>
 <data1>some data</data1>
 <data2>some data</data2>
 <data3>some data</data3>
 <category id="0">
  <categoryName>Cat 1</categoryName>
  <categorydata1>some data</categorydata1>
 </category>
 <category id="1">
  <categoryName>Cat 2</categoryName>
  <categorydata1>some data</categorydata1>
  <categorydata2>some data</categorydata2>
  <categorydata3>some data</categorydata3>
  <categorydata4>some data</categorydata4>
 </category>
</details>

And I want to remove a category that has a specific attribute named id with the DOM class in php when i run a function activated from using a remove button. 当我运行通过使用删除按钮激活的功能时,我想删除具有特定属性id的类别,该类别具有php中的DOM类。

the following is the debug of the function im trying to get to work. 以下是尝试开始工作的功能的调试。 Can i know what I'm doing wrong? 我能知道我在做什么错吗?

function CatRemove($myXML){
        $xmlDoc = new DOMDocument();
        $xmlDoc->load( $myXML );
        $categoryArray = array();

        $main = $xmlDoc->getElementsByTagName( "details" )->item(0);

        $mainElement = $xmlDoc->getElementsByTagName( "details" );
        foreach($mainElement as $details){
            $currentCategory = $details->getElementsByTagName( "category" );
            foreach($currentCategory as $category){
                $categoryID = $category->getAttribute('id');
                array_push($categoryArray, $categoryID);
                if($categoryID == $_POST['categorytoremoveValue']) {
                    return $categoryArray;
                }
            }
        }


        $xmlDoc->save( $myXML );
    }

Well the above prints me an array of [0]->0 all the time when i slot the return outside the if. 好吧,当我将返回值放在if之外时,上面的代码始终会打印[0]-> 0的数组。 is there a better way? 有没有更好的办法? I've tried using getElementbyId as well but I've no idea how to work that. 我也尝试过使用getElementbyId,但我不知道如何工作。

I would prefer not to use an attribute though if that would make things easier. 我宁愿不要使用属性,尽管那样会使事情变得更容易。

Ok, let's try this complete example of use: 好的,让我们尝试一下完整的用法示例:

function CatRemove($myXML, $id) {
    $xmlDoc = new DOMDocument();
    $xmlDoc->load($myXML);
    $xpath = new DOMXpath($xmlDoc);
    $nodeList = $xpath->query('//category[@id="'.(int)$id.'"]');
    if ($nodeList->length) {
        $node = $nodeList->item(0);
        $node->parentNode->removeChild($node);
    }
    $xmlDoc->save($myXML);
}

// test data
$xml = <<<XML
<?xml version="1.0"?>
<details>
 <person>name</person>
 <data1>some data</data1>
 <data2>some data</data2>
 <data3>some data</data3>
 <category id="0">
  <categoryName>Cat 1</categoryName>
  <categorydata1>some data</categorydata1>
 </category>
 <category id="1">
  <categoryName>Cat 2</categoryName>
  <categorydata1>some data</categorydata1>
  <categorydata2>some data</categorydata2>
  <categorydata3>some data</categorydata3>
  <categorydata4>some data</categorydata4>
 </category>
</details>
XML;
// write test data into file
file_put_contents('untitled.xml', $xml);
// remove category node with the id=1
CatRemove('untitled.xml', 1);
// dump file content
echo '<pre>', htmlspecialchars(file_get_contents('untitled.xml')), '</pre>';

So you want to remove the category node with a specific id ? 因此,您要删除具有特定idcategory节点吗?

$node = $xmlDoc->getElementById("12345");
if ($node) {
    $node->parentNode->removeChild($node);
}

You could also use XPath to get the node, for example: 您还可以使用XPath来获取节点,例如:

$xpath = new DOMXpath($xmlDoc);
$nodeList = $xpath->query('//category[@id="12345"]');
if ($nodeList->length) {
    $node = $nodeList->item(0);
    $node->parentNode->removeChild($node);
}

I haven't tested it but it should work. 我还没有测试过,但是应该可以。

the above funciton modified to remove an email from a mailing list 修改了上述功能,从邮件列表中删除了一封电子邮件

function CatRemove($myXML, $id) {
    $xmlDoc = new DOMDocument();
    $xmlDoc->load($myXML);
    $xpath = new DOMXpath($xmlDoc);
    $nodeList = $xpath->query('//subscriber[@email="'.$id.'"]');
    if ($nodeList->length) {
        $node = $nodeList->item(0);
        $node->parentNode->removeChild($node);
    }
    $xmlDoc->save($myXML);
}
$xml = 'list.xml';
$to = $_POST['email'];//user already submitted they email using a form 
CatRemove($xml,$to);

Can you try with this modified version: 您可以尝试使用此修改版本:

function CatRemove($myXML, $id){
    $doc = new DOMDocument();
    $doc->loadXML($myXML);
    $xpath = new DOMXpath($doc);
    $nodeList = $xpath->query("//category[@id='$id']");
    foreach ($nodeList as $element) {
        $element->parentNode->removeChild($element);
    }

    echo htmlentities($doc->saveXML());
}

It's working for me. 它为我工作。 Just adapt it to your needs. 只要适应您的需求即可。 It's not intended to use as-is, but just a proof of concept. 它不是按原样使用的,而只是概念的证明。 You also have to remove the xml declaration from the string. 您还必须从字符串中删除xml声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM