我正在尝试使用PHP文档使用PHP 5的内置SimpleXMLElement类构建XML文档(用于AJAX).我想从一个空白的平板开始并按元素构建XML元素,但是我发现如果SimpleXMLElement不从一些现有的XML代码开始构建一个,我就没有办法.我无法成功地将空字符串("")传递给SimpleXMLElement构造函数,所以目前我正在传递最外层标记的XML,然后从那里构建.这是我的代码:
// 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();
Run Code Online (Sandbox Code Playgroud)
有更清洁的方法吗?