我在脚本中发生错误时生成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;
}
?>
第19行第1行的错误:错误:解析XML声明:'?&gt;'预期
编辑2:删除charset = \“utf-8 \修复它!但是我需要它,所以我很困惑为什么会导致这个问题?
答案 0 :(得分:0)
检查文件编码;确保你使用的是UTF-8,它没有BOM。
答案 1 :(得分:0)
解决了这个问题!
我使用此工具删除空格: http://www.design215.com/toolbox/whitespace.php
我的XML声明中也设置了“charset”,它应该是“编码”。 EG:
<?xml version="1.0" encoding="utf-8"?>
<conv>
<error code="1000">Required parameter is missing</error>
</conv>