2009/03/31

php一行搞定过滤字符


<?php
iconv('GBK', 'GBK//IGNORE', $file);//过滤掉错误字符,防止解析错误
?>


解决问题:如果你的文件中含有错误字符,在执行解析xml等操作时有时会引发解析错误。在解析xml文档时若头部编码为gb2312,尽量替换为gbk。

方法:iconv,将进出编码均设置为同一编码即可,加上'//IGNORE'即可。

优点:省去自己解析字串剔除错误编码,非常方便。

应用场景:

1.使用simplexml_load_file(),simplexml_load_string(),出现错误Premature end of data in tag...。改用file_get_contents(),然后iconv(),再simplexml_load_string()即可。

2.Warning: SimpleXMLElement::__construct() [function.SimpleXMLElement---construct]:
input conversion failed due to input error, bytes 0xC2 0x2E 0x20 0x20 in。。。

没有评论:

发表评论