Question

how do I delete a parent node with php in xml and save changes

what I try

<element>
    <feed id=" 9 ">
        <title>test</title>
        <table>feeds</table>
        <link/>
        <feed_type>API</feed_type>
        <affiliate/>
        <mwst>ja</mwst>
        <tld>DE</tld>
        <query/>
    </feed>
</element>
public function deleteNode($feed_id){

    //find feed on attribute ID
    $node = $this->xml->xpath('//feed[@id =' . $feed_id . ' ]');
    //find the parent and delete thenode
    $element = $node[0]->xpath('parent::*');
    // ??unset($element[0]);
    $this->xml->asXML(SITE_ROOT . '/xml/feed_config.xml');
    exit();
}
Was it helpful?

Solution

Edit #1:

(Thanks to @michi for pointing out that unset is sufficient to delete a node in SimpleXML)

If you want to remove <element>, not <feed> as I previously thought, you can do this:

function deleteNode($feed_id)
{
    $parent=$this->xml->xpath('//*[feed[@id=" '.$feed_id.' "]]');
    unset($parent[0][0]);
}

Online demo
(Works for PHP>=5.2.2)


Original post

You might need DOM for this:

function deleteNode($feed_id)
{
    $node=$this->xml->xpath('//feed[@id=" '.$feed_id.' "]');
    $node=dom_import_simplexml($node[0]);
    $parent=$node->parentNode;
    $parent->removeChild($node);
    $this->xml=simplexml_import_dom($parent->ownerDocument);
}

Online demo
(Noted that since it's not in a class in the demo, I used a global for the purpose of lazy emulation. Avoid global in your actual code.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top