报错:
Warning: SimpleXMLElement::__construct() [function.SimpleXMLElement---construct]:PHP在解析XML文档时发生错误,这个问题很常见,主要是由于在xml文档中含有头部声明编码以外的字符,而php严格按照头部声明的编码来解析xml文档。通常都是GB2312编码发生此情况,我一般是使用正则来修改文档头部编码声明来避免。如下:
input conversion failed due to input error, bytes 0xC2 0x2E 0x20 0x20 in
E:\www\alsobuy.php on line 47
$xml = preg_replace("/(^<\?xml.*encoding.*)GB2312(.*\?>)/iU" ,一般将其修改为GBK即可,GB2312包含的汉字实在太少了。
'${1}GBK${2}' , $xml );
今天却不好使,纳闷了,后来终于发现,该XML文档中含有一个错误字符,根本无法解析。
而在使用正则等处理字符串时,里面含有乱码一般不会报错,估计SimpleXmlElement()是堆栈来完成xml文档解析的,遇到错误字符就挂了。
解决方案:根据具体编码,确定字符内码的范围,遍历一遍,剔除错误的字符。
下面是根据GBK编码范围来剔除的,效果很好。
代码:
<?php
//含有两个错误的字符
$str = "我\x97\x7f鎔ㄅㄈ是德\x82\x09文";
$len = strlen($str);//长度
$new_str = "";
for($i=0; $i <= $len-1 ;$i++) { $s_hex = ord($str[$i]); if( $s_hex <= 0x7f && $s_hex >=0x00 )
{
//ACSII
$new_str .= $str[$i];
}
else if( $s_hex >= 0x81 && $s_hex <=0xfe )
{
//双字节
if( $i == $len-1 ) break;
$i++;
$s_hex = ord($str[$i]);
if( $s_hex >= 0x40 && $s_hex <= 0xfe && $s_hex != 0x7f)
{
$new_str .= $str[$i-1];
$new_str .= $str[$i];
}
}
}
echo $str.'<br/>';
echo $new_str.'<br/>';
?>
效果图:
方便看代码:
更新:
回复删除iconv( "UTF-8", "gb2312//IGNORE" , $FormValues['a'])
ignore的意思是忽略转换时的错误,发现iconv在转换字符"—"到gb2312时会出错,如果没有ignore参数,所有该字符后面的字符串都无法被保存。