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

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?

11
задан hakre 24 June 2013 в 02:22
поделиться