PHP DOMDocument:致命错误:调用未定义的方法DOMElement :: save()
问题描述:
我试图缩进我的XML文件,但我不能因为这个错误。 为什么会出现此问题?PHP DOMDocument:致命错误:调用未定义的方法DOMElement :: save()
这是我的代码:
<?php
$xmlstr = 'xmlfile.xml';
$sxe = new SimpleXMLElement($xmlstr, null, true);
$lastID = (int)$sxe->xpath("//tip[last()]/tipID")[0] + 1;
$tip = $sxe->addChild('tip');
$tip->addChild('tipID', $lastID);
$tip->addChild('tiptitle', 'Title:');
$sxe->asXML($xmlstr);
$xmlDom = dom_import_simplexml($sxe);
$xmlDom->formatOutput = true;
$xmlDom->save($xmlstr);
?>
我已经做了很多的研究,我无法找到答案。
答
的dom_import_simplexml
function回报DOMElement
一个实例,它没有save
方法:之前,请DOM文档。你需要的是一个DOMDocument
,其中确实有一个save
方法。
幸运的是,从一个到另一个很容易,因为DOMElement
是DOMNode
的一种,因此有ownerDocument
property。需要注意的是formatOutput
属性也是DOMDocument
的一部分,所以你需要的是这样的:
$xmlDom = dom_import_simplexml($sxe)->ownerDocument;
$xmlDom->formatOutput = true;
$xmlDom->save($xmlstr);
答
DOMElement没有保存xml的方法,但是DOMDocument没有。
$xmlDom = dom_import_simplexml($sxe);
$dom = new DOMDocument();
$dom_sxe = $dom->importNode($xmlDom, true);
$dom_sxe = $dom->appendChild($xmlDom);
$Dom->formatOutput = true;
echo $dom->saveXML();
@ splash58没有解决它不幸。错误保持不变,但使用saveXML而不是保存。 –