simplexml存在编码问题

最近帮人解答了一个关于simplexml的问题

对方问题描述如下:

他说,他用simplexml_load_file($url)出错..关键是$url地址中有符号点,例如这样的URL: http://www.blog.163.com/ayi.hgj/rss/

我信以为真..就查询了PHP手册..有如下注意信息描述:

Note: Libxml 2 unescapes the URI, so if you want to pass e.g. b&c as the URI parameter a, you have to call simplexml_load_file(rawurlencode(‘http://example.com/?a=‘ . urlencode(‘b&c’))). Since PHP 5.1.0 you don’t need to do this because PHP will do it for you.

大概意思就是说..Libxml2是不进行escapes URI的,PHP 5.1之前的版本是需要自己用ulrencode处理一下.

于是我建议他用用urlencode..

这时我有一个朋友说:他直接用file_get_contents没问题…

于是我就试验了一下代码..果然如此..

发现好像是编码的问题…于是只好用把网站下载过来的文件进行转码..

然后替换xml的encoding,避免解析的时候出问题..

代码如下:

<?php
$rss=file_get_contents(“http://www.blog.163.com/ayi.hgj/rss/“);
$rss=iconv( “GBK”,”UTF-8″, $rss);
$rss=str_replace(“GBK”,”UTF-8″,$rss);
$rss=simplexml_load_string($rss);

print_r( $rss);
?>

代码如上..结果有问题……

后来想了想..应该tmd是iconv的问题..

<?php
$rss=file_get_contents(“http://www.blog.163.com/ayi.hgj/rss/“);

$rss = mb_convert_encoding($rss, ‘UTF-8′, ‘GBK’);
//$rss=iconv( “GBK”,”UTF-8″, $rss);
$rss=str_replace(“GBK”,”UTF-8″,$rss);
$rss=simplexml_load_string($rss);

print_r( $rss);
?>

一切OK…

总结要点:simplexml用的是xmllib2,xmllib2跟iconv一样..应该是一个处理编码方式,所以有编码问题,

但是UTF-8,老外是经常使用的,所以问题不大..换言之,此为非英文世界专有之问题..

简单来说就一句话..以后遇到GBK的xml最好用utf-8处理..

4 Comments

神仙二月 8th, 2008 at 10:04 下午

我一般都是分两步的,测试方便

Reply

小路 reply on 二月 9th, 2008:

晕死,你这种习惯也挺BT的

Reply

lightsaber二月 14th, 2008 at 9:48 上午

我以前也没注意到simplexml的编码问题,因为一直是用utf-8比较多

Reply

小路 reply on 二月 14th, 2008:

反正用一概都用UTF-8准没错..特别是PHP6将要步入UNICODE时代..

Reply

Leave a comment

Your comment

Comment spam protected by SpamBam