2016-05-17 111 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(); 
相關問題