我的PHP代码中有这个
header('Content-disposition: attachment; filename="'.$filename.'"');
header('Content-type: "text/xml"; charset="utf8"');
readfile($filename);
下载后和我的文件
<?xml version="1.0" encoding="UTF-8"?>
<root>
在文档前面有2或3个空格,我找不到解决方案
当我打开文件时这是一个错误:
This page contains the following errors:
error on line 1 at column 6: XML declaration allowed only at the start of the document
Below is a rendering of the page up to the first error.
并且服务器中的xml文件是正确的
写入文件的函数:
public function toXML($filename){
$qr = mysql_query("select * from passwords where user = '".encrypt($_SESSION['username'],$key)."'");
$xml = '<?xml version="1.0" encoding="UTF-8"?>'."\n";
$xml .= "<root>";
$xml .= "\n";
if (!$qr) {
die('Invalid query: ' . mysql_error());
}
if(mysql_num_rows($qr)>0)
{
while($result_array = mysql_fetch_assoc($qr))
{
$xml .= '<passwords>';
$xml .= "\n";
foreach($result_array as $key => $value)
{
$xml .= "<$key>";
$xml .= "$value";
$xml .= "</$key>";
$xml .= "\n";
}
$xml.="</passwords>\n";
}
}
$xml .= '</root>';
$fp = fopen($filename,"w");
fputs($fp,$xml);
fclose($fp);
return true;
}
和其他php文件
if(!$r->toXML($filename))
$msg = 'Failed to export';
else{
$text = file_get_contents($filename);
$bom = pack('H*','EFBBBF');
$text = preg_replace("/^$bom/", '', $text);
header('Content-disposition: attachment; filename="'.$filename.'"');
header('Content-type: "text/xml"; charset="utf8"');
echo $text;
exit();
}
来自服务器的文件($ filename文件)
<?xml version="1.0" encoding="UTF-8"?>
<root>
<passwords>
<id>8</id>
<title>vbghjbhv</title>
<account>o0H0uTtsOFCYHTpiZZ2/J78W/Z+xU10nx5AUZdcUvdU=</account>
<password>2vOF9Kp2p88IbbIuHcFJeaOc1VJi40KkrAtPIEV5exg=</password>
<url>jhbvgi</url>
<user>2PTpbCnciq+dbuEcyP6v6tZxrQeXcJfRl33YfQO3aFk=</user>
<category>Business</category>
<note>ghujhvgty</note>
</passwords>
</root>
答案 0 :(得分:0)
一种解决方案是将文件存储在变量中, 然后在输出文件内容之前使用trim()。
$file = file_get_contents($filename);
echo trim($file);
答案 1 :(得分:0)
首先,检查您正在使用的文件是否保存在正确的字符集中(没有BOM的UTF-8)。
其次,我们没有看到$ filename的实际填充内容。让我们说它们在$ contents变量中。也许你这样填写:
$contents .= '
... something ';
确保在填充时删除空白行并将其写为:
$contents .= '... something ';