php使用iconv进行从utf-8转为gb2312字符编码出错解决方案

在php函数库有一个函数:iconv()

把gb2312置换成utf-8

$text=iconv("GB2312","UTF-8",$text);

在用$text=iconv(“UTF-8″,”GB2312″,$text)过程中,如果遇到一些特别字符时,如:”—”,英文名中的”.”等等字符,转换就断掉了。这些字符后的文字都没法继续转换了。

针对这的问题,可以用如下代码实现

$text=iconv("UTF-8","GBK",$text);

你没有看错,就这么简单,不使用gb2312,而写成GBK,就可以了。

还有一种方法:

第二个参数,加上//IGNORE,忽略错误,如下:

iconv("UTF-8","GB2312//IGNORE",$data);

没有具体比较这两种方法,感觉第一种(GBK代替gb2312)方法更好.

php手册中iconv() 说明

 

iconv

(PHP 4 >= 4.0.5, PHP 5)

iconv – Convert string to requested character encoding

Description

string iconv ( string in_charset, string out_charset, string str )

Performs a character set conversion on the string str from in_charset to out_charset. Returns the converted string or FALSE on failure.

If you append the string //TRANSLIT to out_charset transliteration is activated. This means that when a character can’t be represented in the target charset, it can be approximated through one or several similarly looking characters. If you append the string //IGNORE, characters that cannot be represented in the target charset are silently discarded. Otherwise, str is cut from the first illegal character.

例子 1. iconv() example:

 

<?php
echo iconv(“ISO-8859-1″, “UTF-8″, “This is a test.”);
?>

 

 

posted @ 2010-11-01 10:02  wgw8299  阅读(1858)  评论(0编辑  收藏  举报