使用php输出xml


output xml using php

我对使用php输出xml感到困惑,我想打印原始xml

<?php 
header('Content-type: text/xml');
$xml="<?xml version='"1.0'" encoding='"UTF-8'"?>";
$xml.="<entry>";
$xml.="<dataset>";
$xml.="</dataset>";
$xml.="</entry>";
print ($xml);
XML Parsing Error: XML or text declaration not at start of entity
Location: http://localhost/api/dataset/11111
Line Number 3, Column 1:<?xml version="1.0" encoding="UTF-8"?><entry><dataset></dataset></entry>
                        ^

但是当我用改变它的时候

<?php 
header('Content-type: text/xml');
$xml="<root><name>sample_name</name></root>";
print ($xml);

它工作,但后来我添加了xml版本和编码信息,它再次出现错误

<?php 
header('Content-type: text/xml');
$xml="<?xml version='"1.0'" encoding='"UTF-8'"?>";
$xml.="<root><name>sample_name</name></root>";
print ($xml);
XML Parsing Error: XML or text declaration not at start of entity
Location: http://localhost/api/dataset/100039
Line Number 3, Column 1:<?xml version="1.0" encoding="UTF-8"?><root><name>sample_name</name></root>

它似乎无法添加标题信息,也无法使用字符串串联运算符???我如何像打印xml一样打印带有标题的xml('Content-type:text/xml')

<?xml version="1.0" encoding="UTF-8"?>
<entry>
   <dataset>
   </dataset>
</entry>

我使用yii框架actionView

$this->renderPartial('view',array('model'=>$model,'type'=>$type));

当我在源代码中检查这个错误时,它可以看到xml信息,但在?之前有两行空白??,也许这是XML解析错误的原因,但我如何删除那些空行呢?在view.php和action函数中,我没有找到任何echo/print空行。

 XML Parsing Error: XML or text declaration not at start of entity
    Location: http://localhost/api/dataset/11111
    Line Number 3, Column 1:<?xml version="1.0" encoding="UTF-8"?><entry><dataset></dataset></entry>
                        ^

您可以执行以下操作:

<?php
echo <<<END
<?xml version="1.0" encoding="UTF-8"?>
<entry>
   <dataset>
   </dataset>
 </entry>
END
?>

或者你可以这样做:

<?xml version="1.0" encoding="UTF-8"?>
<entry>
   <dataset>
<?php
  /* We can put code for something here */
?>
   </dataset>
 </entry>

为什么不使用'来封装xml文本,这样您的"就可以在文本中使用。还可以使用特殊的字符函数,这样html就不会认为这是一个代码。

$xml = '<?xml version="1.0" encoding="UTF-8"?><entry><dataset></dataset></entry>';
echo htmlspecialchars($xml, ENT_XML1);

我注意到你的标题内容类型是小写字母。我不知道这是否重要。你能换成大写吗?

header('Content-Type: text/xml');