XML文档开头的空白导致了错误


whitespace at start of XML doc is causing error

当脚本中出现错误时,我正在生成一个XML响应,但是XML响应包含错误"仅在文档开头允许XML声明"。从我所做的研究中,我发现这是由打开XML声明之前的空白引起的。(这正是我的XML响应。)

 <?xml version="1.0" charset="utf-8"?>
<conv>
    <error code="1000">Required parameter is missing</error>
</conv>

然而,我找不到这个问题的根源?以下是生成响应的代码:

function result($data,$errnum,$type='XML') {
    switch(strtolower($type)) {     
        case 'xml':
            // Build the XML body
            header('Content-Type: text/xml');               
            $xmlpage = "<?xml version='"1.0'" charset='"utf-8'"?>'n";
            $xmlpage .= "<conv>'n";
            $xmlpage .= "'t<error code='"$errnum'">$data</error>'n";
            $xmlpage .= '</conv>';
            echo $xmlpage;              
        break;
    }
    exit;
}

有什么想法吗?

编辑-

我通过一个空白删除工具运行了这个页面,它在一开始就删除了空白,但我现在遇到了一个新错误:

<?php
function error($errnum=1000) {
$data = array(
'1000' => 'Required parameter is missing',
'1100' => 'Parameter not recognized',
'2000' => 'Currency type not recognized',
'2100' => 'Currency amount must be to 2 decimal places',
'2200' => 'Currencies cannot be the same',
'3000' => 'Service currently unavailable',
'3100' => 'Error in service'
);
result($data[$errnum], $errnum);
}
function result($data,$errnum,$type='XML') {
switch(strtolower($type)) {
case 'xml':
// Build the XML body
header('Content-Type: text/xml');
$xmlpage = "<?xml version='"1.0'" charset='"utf-8'"?>'n";
$xmlpage .= "<conv>'n";
$xmlpage .= "'t<error code='"$errnum'">$data</error>'n";
$xmlpage .= '</conv>';
echo $xmlpage;
break;
}
exit;
}
?>

错误:第1行第19列出现错误:正在分析XML声明:"?>'预期

编辑2:删除charset=''"utf-8''修复了它!但我需要它,所以我很困惑为什么会导致问题?

解决了这个问题!

我使用此工具删除空白:http://www.design215.com/toolbox/whitespace.php

我还在XML声明中设置了"charset",它应该是"编码"的。例如:

<?xml version="1.0" encoding="utf-8"?>
<conv>
    <error code="1000">Required parameter is missing</error>
</conv>

检查文件编码;如果您使用UTF-8,请确保它没有BOM。