Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an empty/blank SimpleXMLElement in PHP?

Tags:

php

simplexml

I am trying to use a PHP document to construct an XML document (for AJAX) using PHP 5's built-in SimpleXMLElement class. I want to start with a blank slate and build the XML element by element, but I have found no way to construct a SimpleXMLElement without starting from some existing piece of XML code. I wasn't able to successfully pass in a blank string ("") to the SimpleXMLElement constructor, so currently I'm passing in the XML for the outermost tag, and then building from there. Here's my code:

// Start with a "blank" XML document.
$xml = new SimpleXMLElement("<feature></feature>");

// Add various children and attributes to the main tag.
$xml->addAttribute("id", $id);
$xml->addChild("title", $feature['title']);
$xml->addChild("summary", $feature['summary']);
// ...

// After the document has been constructed, echo out the XML.
echo $xml->asXML();

Is there a cleaner way to do this?

like image 589
andrewtc Avatar asked Dec 23 '10 07:12

andrewtc


1 Answers

As salathe mentioned:

The clue is in the class name, you're creating SimpleXML elements.

It makes sense to me now that a SimpleXMLElement cannot be "empty". It must be a valid XML element, which entails having a tag name and opening and closing tags (e.g. <feature></feature> or <body></body>).

This would seem to imply that SimpleXMLElement was created for parsing, rather than building, XML documents. That being said, I found it very easy to build a document from scratch. The class does a lot of nice things automatically, including keeping everything compact and outputting the XML version number at the top (<?xml version="1.0"?>).

I would recommend this approach to anyone who needs to use PHP to construct small XML documents. It beats echoing out the tags as strings any day.

Thank you, everyone, for your comments!

like image 117
andrewtc Avatar answered Sep 20 '22 08:09

andrewtc