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

故事扮演 提交于 2019-12-01 14:20:06

问题


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?


回答1:


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!



来源:https://stackoverflow.com/questions/4516657/how-do-i-create-an-empty-blank-simplexmlelement-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!