显示标签为“xml”的博文。显示所有博文
显示标签为“xml”的博文。显示所有博文

2008/11/26

php serialize and serialize SimpleXMLElement

在PHP5中,序列化/反序列化simpleXMLElement对象时发生Warning: unserialize() [function.unserialize]: Node no longer exists in...的错误。

查了一下,http://bugs.php.net/bug.php?id=46143&edit=1,里面有段描述:

AFAIK, you cannot serialize a SimpleXMLElement, because it's a resource wrapped inside an object and it would be impossible de restore thatresource upon unserialize()-ation. That's why you receive an error: theunserialized object doesn't know where's the original document anymore.Store it in text form instead (asXML()).
说是SimpleXMLElement这个对象内部是包装的资源,即php中的resource类型,而resource是不可以序列化的。

上述文字提供了一个解决方案,保存其xml字符串,然后再通过simplexml_load_file/simplexml_load_string恢复SimpleXMLElement对象即可,xml字符串可以通过SimpleXMLElement->asXML()得到。

2008/11/11

SimpleXMLElement解析报错解决方案:剔除字符串中错误字符

实在不愿意写关于PHP乱码方面的东西了,今天再次遇到了一个很郁闷的问题,字符串中含有错误的字码(内码)。

报错:
Warning: SimpleXMLElement::__construct() [function.SimpleXMLElement---construct]:
input conversion failed due to input error, bytes 0xC2 0x2E 0x20 0x20 in
E:\www\alsobuy.php on line 47
PHP在解析XML文档时发生错误,这个问题很常见,主要是由于在xml文档中含有头部声明编码以外的字符,而php严格按照头部声明的编码来解析xml文档。通常都是GB2312编码发生此情况,我一般是使用正则来修改文档头部编码声明来避免。如下:
$xml = preg_replace("/(^<\?xml.*encoding.*)GB2312(.*\?>)/iU" ,
'${1}GBK${2}' , $xml );
一般将其修改为GBK即可,GB2312包含的汉字实在太少了。

今天却不好使,纳闷了,后来终于发现,该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/>';
?>



效果图:


方便看代码: