[英]How to save changed SimpleXML object back to file?
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. 因此,我有这段代码可以搜索我的XML文件中的特定节点,取消设置现有节点并插入带有正确数据的全新子节点。 Is there a way of getting this new data to save within the actual XML file with simpleXML?
有没有一种方法可以使用simpleXML将这些新数据保存在实际的XML文件中? 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;
}
}
}
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. asXML()
方法接受可选的文件名作为参数,该参数会将当前结构作为XML保存到文件中。 So once you have updated your XML with the hints, just save it back to file. 因此,使用提示更新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');
If you want to save the same, you can use dom_import_simplexml
to 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.