我正在尝试使用PHP文档构建一个使用PHP 5的内置SimpleXMLElement
类的XML文档(用于AJAX)。我想从一个空白的石板开始,逐个构建XML元素,但是我没有办法构建一个SimpleXMLElement
,而没有从现有的一段XML代码开始。我无法成功地将一个空白字符串(“”)传递给构造函数SimpleXMLElement
,所以目前我将XML传递给最外层的标记,然后从那里构建。这里是我的代码:如何在PHP中创建一个空/空的SimpleXMLElement?
// 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();
有没有更干净的方法来做到这一点?
您可以使用DOMDocument创建元素并将其转换为SimpleXML,但这甚至更加复杂...... – derekerdmann 2010-12-23 07:30:17
线索在类名中,您正在创建SimpleXML *元素*。至于更干净,`simplexml_import_dom()`是不必要的。除此之外,如果你想通过单个元素/属性来构建文档,那么你拥有的是好的。 – salathe 2010-12-23 08:25:56