2016-05-17 45 views
0

我试图缩进我的XML文件,但我不能因为这个错误。 为什么会出现此问题?PHP DOMDocument:致命错误:调用未定义的方法DOMElement :: save()

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

?> 

我已经做了很多的研究,我无法找到答案。

+0

@ splash58没有解决它不幸。错误保持不变,但使用saveXML而不是保存。 –

回答

0

dom_import_simplexml function回报DOMElement一个实例,它没有save方法:之前,请DOM文档。你需要的是一个DOMDocument,其中确实有一个save方法。

幸运的是,从一个到另一个很容易,因为DOMElementDOMNode的一种,因此有ownerDocument property。需要注意的是formatOutput属性也是DOMDocument的一部分,所以你需要的是这样的:

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

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(); 
相关问题