PHP DOMDocument:致命错误:调用未定义的方法DOMElement :: save()

时间:2016-05-17 10:13:17

标签: php simplexml domdocument

我试图缩进我的XML文件,但我不能因为这个错误。 为什么会出现此问题?

The problem

这是我的代码:

<?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);

?>

我做了很多研究,但我找不到答案。

2 个答案:

答案 0 :(得分:1)

DOMElement没有保存xml的方法,但是DOMDocument没有。之前制作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();

答案 1 :(得分:0)

dom_import_simplexml function会返回DOMElement的实例,该实例没有save方法。您需要的是DOMDocument,其中 具有save方法。

幸运的是,从一个到另一个很容易,因为DOMElement是一种DOMNode,因此有一个ownerDocument property。请注意,formatOutput属性也是DOMDocument的一部分,因此您需要的是:

$xmlDom = dom_import_simplexml($sxe)->ownerDocument;
$xmlDom->formatOutput = true;
$xmlDom->save($xmlstr);