• Working with DOM in PHP – Add elements to XML

    Posted by markzero on Sunday, January 9th, 2011

    It’s almost unavoidable in web programming to work with XML. We can retrieve an XML structure from string or a file. But, what if we want to change it, e.g. to add, remove, change elements or attributes or whatever. In that case DOM (Document Object Model) is used. What we do is, create document, load XML from any source, and do what you have to.

    To generate a DOM, put this:

    <?php $doc = new DOMDocument('1.0','utf-8'); ?>

    This will create XML root, like: <?xml version=”1.0″ encoding=”utf-8″?>. Let’s say you have a string $xmlstring and $element as mixed variable to represent a new element, so after we created a root, next is to load string in XML form:

    <?php $newEl = $doc->createElement("elementName",$element); ?>

    That’s it, you’ve added an element to the DOM. Now we can get final result by getting string from DOM:

    <?php $doc->saveXML(); ?>

    There is one catch though… This will return string WITH root (<?xml … ?&gtl). I figured, like this string is 22 characters in length (if utf-8 is used), so this

    <?php $xml = substr($doc->saveXML(),22,strlen($doc->saveXML())); ?>

    will return the whole string without the stupid root at top ;)

    Hope you found something useful in this post.

    Posted in: DOM, PHP, XML.

    Share this story:

    Leave a Reply