Search code examples
phpxmlxpathremovechild

Remove XML child with same name


I have a large XML with the following:

<?xml version="1.0" encoding="UTF-8"?>
<valasz xmlns="" verzio="1.0">
<arak>
<ar>
<cikkid>439902</cikkid>
<cikkszam>DVDV-16Z10</cikkszam>
<listaar>1225,0000000</listaar>
<ar>1157,6200000</ar>
<akcios_ar>1157,6200000</akcios_ar>
<devizanem>HUF</devizanem>
</ar>
<ar>
..
<ar>1157,6200000</ar>
...
</ar>
</arak>

What i want is to remove arak->ar->ar child because its causing in the import it looks like duplicates, and slowing down the process.

I have tried the following:

    $node = readfile($arlista[0]);
    $nodes = simplexml_load_string($node);
    $arnode = $nodes->xpath("/valasz/arak/ar/ar");
        foreach ($arnode as &$ar){
            $nodes->removeChild($ar);
        }
    echo $nodes;

And this only returns me the original xml, without removing the arak->ar->ar child nodes.

What am i doing wrong?


Solution

  • There is no such thing as ::removeChild() in SimpleXML. What you want do do in your foreach loop is this:

    foreach ($arnode as $ar){
        unset($ar->{0});
    }
    

    Please note: The posted XML is not valid but I am sure that is just some kind of copy&paste flaw

    Complete code:

    $xml = '<?xml version="1.0" encoding="UTF-8"?>
                <valasz xmlns="" verzio="1.0">
                    <arak>
                        <ar>
                            <cikkid>439902</cikkid>
                            <cikkszam>DVDV-16Z10</cikkszam>
                            <listaar>1225,0000000</listaar>
                            <ar>1157,6200000</ar>
                            <akcios_ar>1157,6200000</akcios_ar>
                            <devizanem>HUF</devizanem>
                        </ar>
                        <ar>
                            <ar>1157,6200000</ar>
                        </ar>
                    </arak>
                </valasz>';
    $nodes = simplexml_load_string($xml);
    $arnode = $nodes->xpath("/valasz/arak/ar/ar");
    foreach ($arnode as $ar){
        unset($ar->{0});
    }
    print_r($nodes); 
    

    Returns this SimpleXMLElement Object ( [@attributes] => Array ( [verzio] => 1.0 )

        [arak] => SimpleXMLElement Object
            (
                [ar] => Array
                    (
                        [0] => SimpleXMLElement Object
                            (
                                [cikkid] => 439902
                                [cikkszam] => DVDV-16Z10
                                [listaar] => 1225,0000000
                                [akcios_ar] => 1157,6200000
                                [devizanem] => HUF
                            )
    
                        [1] => SimpleXMLElement Object
                            (
                            )
    
                    )
    
            )
    
    )