如何将更改后的SimpleXML对象保存回文件?

Thi*_*its 34 php xml simplexml

所以,我有这个代码在我的XML文件中搜索特定节点,取消设置现有节点并插入具有正确数据的全新子节点.有没有办法使用simpleXML将这些新数据保存在实际的XML文件中?如果没有,还有另一种有效的方法吗?

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;

        }

    }

}
Run Code Online (Sandbox Code Playgroud)

Gor*_*don 65

我不确定我是否理解这个问题.该asXML()方法接受一个可选的文件名作为param,将当前结构作为XML保存到文件中.因此,一旦使用提示更新了XML,只需将其保存回文件即可.

// 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');
Run Code Online (Sandbox Code Playgroud)