SimpleXMLElement不会创建正确的子项

时间:2013-06-06 17:48:53

标签: php simplexml

我正在使用 simpleXMLElement 来创建新的xml文件。 我想创建类似于以下内容的东西:

<?xml version="1.0"?>
<command type="scenario" name="test">
    <game type="play" filename="google">
    </game>
</command>

我正在使用此代码,但有些不正确:

<?php

$xml = new SimpleXMLElement("<?xml version=\"1.0\" ?><command type='scenario'></command>"); 
$xml->addAttribute('name', 'test');
$game = $xml->addChild('game');
$game->addAttribute('type', 'play');
$game->addAttribute('filename', 'google');

// checking the output
$handler = fopen(sad.xml, 'w');
fwrite($handler, $xml->asXML());
fclose($handler);

?>

但这是我在sad.xml文件中看到的输出:

<?xml version="1.0"?>
<command type="scenario" name="test"><game type="play" filename="google"/></command>

为什么?

  1. 新行没有出现在文件
  2. 游戏标记没有</game>结束标记

2 个答案:

答案 0 :(得分:0)

试试这个。

$game = new SimpleXMLElement('', LIBXML_NOEMPTYTAG);    
$xml->addChild($game);

您可以在PHP simpleXML how to save the file in a formatted way?

找到格式化输出的解决方案

答案 1 :(得分:0)

@lexicus解释了如何实现您想要的输出。在回答你的问题时,&#34;为什么?&#34;,你的样本文件和SimpleXML输出之间在逻辑上没有区别:

  1. XML解析器忽略标记之间的空格。如果两个标签相邻(<tag1><tag2/></tag1>)或由57,392,391个空行分隔,则无关紧要;所有解析器都会看到XML元素。
  2. <game/>只是<game></game>的XML简写。 />明确表示它是一个空标记。
  3. 您不是在SimpleXML中编写文档;您正在构建XML树。当你致电->asXML()时,它会以最简单的方式写出树。