简体   繁体   English

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

[英]PHP DOMDocument: Fatal error: Call to undefined method DOMElement::save()

I'm trying to indent my XML file, but I can't because of this error. 我正在尝试缩进XML文件,但是由于这个错误,我不能。 Why is this problem appear? 为什么会出现此问题?

问题

This is my code: 这是我的代码:

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

?>

I've done a lot of research and I couldn't find an answer. 我已经做了大量研究,但找不到答案。

DOMElement has not method to save xml, but DOMDocument does. DOMElement没有保存xml的方法,但是DOMDocument有。 Make DOMDocument before: 在制作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();

The dom_import_simplexml function returns an instance of DOMElement , which has no save method. dom_import_simplexml函数返回DOMElement的实例,该实例没有save方法。 What you need instead is a DOMDocument , which does have a save method. 相反,您需要的是DOMDocument ,它确实具有save方法。

Luckily, it's really easy to get from one to the other, because a DOMElement is a type of DOMNode , and so has an ownerDocument property . 幸运的是,彼此之间真的很容易,因为DOMElementDOMNode ,并且具有ownerDocument属性 Note that the formatOutput attribute is also part of the DOMDocument , so what you need is this: 请注意, formatOutput属性也是DOMDocument一部分,因此您需要的是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM