How to save changed SimpleXML object back to file?

前端 未结 2 1480
迷失自我
迷失自我 2020-12-02 13:35

So, I have this code that searches for a particular node in my XML file, unsets an existing node and inserts a brand new child node with the correct data. Is there a way of

相关标签:
2条回答
  • 2020-12-02 13:42

    Not sure I understand the issue. The asXML() method accepts an optional filename as param that will save the current structure as XML to a file. So once you have updated your XML with the hints, just save it back to file.

    // Load XML with SimpleXml from string
    $root = simplexml_load_string('<root><a>foo</a></root>');
    // Modify a node
    $root->a = 'bar';
    // Saving the whole modified XML to a new filename
    $root->asXml('updated.xml');
    // Save only the modified node
    $root->a->asXml('only-a.xml');
    
    0 讨论(0)
  • 2020-12-02 13:50

    If you want to save the same, you can use dom_import_simplexml to convert to a DomElement and save:

    $dom = new DOMDocument('1.0');
    $dom->preserveWhiteSpace = false;
    $dom->formatOutput = true;
    $dom->loadXML($simpleXml->asXML());
    echo $dom->saveXML();
    
    0 讨论(0)
提交回复
热议问题