Search code examples
phpsimplexmldomdocument

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. Why is this problem appear?

The problem

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.


Solution

  • The dom_import_simplexml function returns an instance of DOMElement, which has no save method. What you need instead is a DOMDocument, which does have a save method.

    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. Note that the formatOutput attribute is also part of the DOMDocument, so what you need is this:

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