php 第 1 行第 6 列错误:仅在文档开头允许 XML 声明
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21261627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
error on line 1 at column 6: XML declaration allowed only at the start of the document
提问by nitroman
I was trying to build an XML file. But stuck with an error. I am including the code and error. Thanks in advance.
我试图构建一个 XML 文件。但是遇到了一个错误。我包括代码和错误。提前致谢。
<?php
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("comrade") or die(mysql_error());
$data = mysql_query("SELECT * FROM support WHERE DATE(`date`) = CURDATE()")
or die(mysql_error());
$xml = new SimpleXMLElement('<xml/>');
while($info = mysql_fetch_array( $data ))
{
$support = $xml->addChild('support');
$support->addChild('cus_name',$info['com_name']);
$support->addChild('ser_type',$info['ser_type']);
}
Header('Content-type: text/xml');
print($xml->asXML());
?>
It showing the following error
它显示以下错误
Below is a rendering of the page up to the first error.
回答by Elia Weiss
In short, you should do:
简而言之,你应该这样做:
ob_clean(); //Clean (erase) the output buffer
print($xml->asXML());
explain: if any of the included files print a new line you will get
解释:如果任何包含的文件打印一个新行,你会得到
error on line 2 at column 6: XML declaration allowed only at the start of the document
第 2 行第 6 列错误:仅在文档开头允许 XML 声明
it could be because in some file the <?phptag start after an empty line.
这可能是因为在某些文件中,<?php标记在空行之后开始。
so instead of searching the file that cause the error, simply clean the output buffer.
因此,无需搜索导致错误的文件,只需清理输出缓冲区即可。
回答by MonkeyZeus
Your issue is the placement of Header('Content-type: text/xml');
你的问题是放置 Header('Content-type: text/xml');
Try this and make sure NOTHINGcomes before the header()call:
试试这个并确保在调用之前没有任何内容header():
<?php
header('Content-type: text/xml');
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("comrade") or die(mysql_error());
$data = mysql_query("SELECT * FROM support WHERE DATE(`date`) = CURDATE()")
or die(mysql_error());
$xml = new SimpleXMLElement('<xml/>');
while($info = mysql_fetch_array( $data ))
{
$support = $xml->addChild('support');
$support->addChild('cus_name',$info['com_name']);
$support->addChild('ser_type',$info['ser_type']);
}
print($xml->asXML());
?>
回答by Mike Ivy
Sometimes saving UTF-8 with/without BOM could solve this (and similar) issues. Some special byte could exist in the very beginning of file in case of wrong saving method.
有时使用/不使用 BOM 保存 UTF-8 可以解决这个(和类似的)问题。如果保存方法错误,文件开头可能会存在一些特殊字节。

