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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3418376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:40:30  来源:igfitidea点击:

How to save changed SimpleXML object back to file?

phpxmlsimplexml

提问by ThinkingInBits

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?

所以,我有这段代码在我的 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;

        }

    }

}

回答by Gordon

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.

不确定我理解这个问题。该asXML()方法接受一个可选的文件名作为参数,它将当前结构作为 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');

回答by Sarfraz

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

如果要保存相同,可以使用dom_import_simplexml转换为 DomElement 并保存:

$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($simpleXml->asXML());
echo $dom->saveXML();