Search code examples
phpxmlxpathsimplexml

Delete XML node with SimpleXML, PHP


I'm trying to delete XML node with PHP (SimpleXML).

This is my XML:

<?xml version="1.0"?>
<items>
    <a>
        <name>A1</name>
        <b>
            <title>Item1</title>
            <url>item1</url>
        </b>
        <b>
            <title>Item2</title>
            <url>item2</url>
        </b>
        <b>
            <title>Item3</title>
            <url>item3</url>
        </b>
    </a>
    <a>
        <name>A2</name>
        <b>
            <title>Item1</title>
            <url>item1</url>
        </b>
    </a>
</items>    

and this is my PHP code:

<?php
    $xml = simplexml_load_file($_GET["xml"]);
    $sxe = new SimpleXMLElement($xml->asXML());


    $ID = $_GET["ID"];
    $i = -1;
    $num = $_GET["num"];

    foreach ($sxe->children() as $var) {
        if ($var == $ID) {
            foreach ($var->children() as $data) {
                if ($data == "link") {
                    $i++;

                    if ($i == $num) {
                        if ( ! empty($sxe)) {
                            unset($sxe[0]);
                        }
                    }
                }
            }
        }
    }

    $sxe->asXML($_GET["xml"]);  
?>

This code looks for with data of $ID (for example, $ID="A1"). The node it looks to delete is a node (with its and ), which is the #$num node.

Example: if $ID="A1" and $num=1, it needs to delete the node with the title "Item2" and url "item2".

What am I doing wrong?

Thanks!


Solution

  • Use xpath to find a node. With your example it will be

    //a[name="A1"]/b[2]
    

    and use DomDocument method removeChild to change xml

    $sxe = simplexml_load_string($xml);
    $node = $sxe->xpath('//a[name="'. $ID .'"]/b['. $num .']');
    $dom=dom_import_simplexml($node[0]);
    $dom->parentNode->removeChild($dom);
    echo $sxe->asXML();