38

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 getting this new data to save within the actual XML file with simpleXML? If not, is there another efficient method for doing this?

public function hint_insert() {

    foreach($this->hints as $key => $value) {

        $filename = $this->get_qid_filename($key);

        echo "$key - $filename - $value[0]<br>";

        //insert hint within right node using simplexml
        $xml = simplexml_load_file($filename);

        foreach ($xml->PrintQuestion as $PrintQuestion) {

            unset($xml->PrintQuestion->content->multichoice->feedback->hint->Passage);

            $xml->PrintQuestion->content->multichoice->feedback->hint->addChild('Passage', $value[0]);

            echo("<pre>" . print_r($PrintQuestion) . "</pre>");
            return;

        }

    }

}
ThinkingInBits
  • 10,792
  • 8
  • 57
  • 82

2 Answers2

74

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');
Jason
  • 13,606
  • 2
  • 29
  • 40
Gordon
  • 312,688
  • 75
  • 539
  • 559
3

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();
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • So looking at my code above, this will save my updated $xml object to whatever $filename is? – ThinkingInBits Aug 05 '10 at 19:37
  • I tried changing it to $dom = new DOMDocument('1.0'); $dom->preserveWhiteSpace = false; $dom->formatOutput = true; $dom->loadXML($xml->asXML()); $dom->save($filename); But still no update in the file – ThinkingInBits Aug 05 '10 at 19:41
  • Ok, actually it does work now with the $dom->save($filename)... Thanks! – ThinkingInBits Aug 05 '10 at 19:45
  • @Sarfraz Your example does not use `dom_import_simplexml`. You are loading the XML string from `asXML()`, which is the function to output or **save a file** with SimpleXml, so why DOM? The only advantage of using DOM is you can format the output, which is only needed when people are authoring it by hand. – Gordon Aug 05 '10 at 20:06
  • @Gordon: I forgot to add that line but later after seeing the OP's comment he said it worked, then i didn't write anymore otherwise yes it was needed and that is now there with your comment for OP if he wishes. – Sarfraz Aug 05 '10 at 20:09