教程集 www.jiaochengji.com
教程集 >  脚本编程  >  php  >  正文 php编码转换函数例解

php编码转换函数例解

发布时间:2018-03-05   编辑:jiaochengji.com
本文介绍了php编码转换函数的用法,包括mb_convert_encoding、iconv函数的用法,有需要的朋友参考下。

在php编程中,mb_convert_encoding函数是用来转换编码的。

不过英文一般不会存在编码问题,只有中文数据才会有这个问题。

比如用zend studio或editplus写程序时,用的是gbk编码,如果数据需要入数据库,而数据库的编码为utf8时,这时就要把数据进行编码转换,不然进到数据库就会变成乱码。

mb_convert_encoding的用法见官方:
http://cn.php.net/manual/zh/function.mb-convert-encoding.php

1,gbk to utf-8 编码转换
 

复制代码 代码示例:
< ?php
header("content-type: text/html; charset=utf-8");
echo mb_convert_encoding("妳係我的友仔", "utf-8", "gbk");
?>

2,gb2312 to big5 编码转换
 

复制代码 代码示例:
< ?php
header("content-type: text/html; charset=big5");
echo mb_convert_encoding("你是我的朋友", "big5", "gb2312");
?>
 

不过要使用上面的函数需要安装但是需要先enable mbstring 扩展库。

php中的另外一个函数iconv也是用来转换字符串编码的,与上函数功能相似。

例子:
 

iconv — convert string to requested character encoding
(php 4 >= 4.0.5, php 5)
mb_convert_encoding — convert character encoding
(php 4 >= 4.0.6, php 5)

用法:
string mb_convert_encoding ( string str, string to_encoding [, mixed from_encoding] )
需要先enable mbstring 扩展库,在 php.ini里将; extension=php_mbstring.dll 前面的 ; 去掉
mb_convert_encoding 可以指定多种输入编码,它会根据内容自动识别,但是执行效率比iconv差太多;

string iconv ( string in_charset, string out_charset, string str )
注意:第二个参数,除了可以指定要转化到的编码以外,还可以增加两个后缀://translit 和 //ignore,其中 //translit 会自动将不能直接转化的字符变成一个或多个近似的字符,//ignore 会忽略掉不能转化的字符,而默认效果是从第一个非法字符截断。
returns the converted string or false on failure.

使用:
发现iconv在转换字符”—”到gb2312时会出错,如果没有ignore参数,所有该字符后面的字符串都无法被保存。不管怎么样,这个”—”都无法转换成功,无法输出。 另外mb_convert_encoding没有这个bug.

一般情况下用 iconv,只有当遇到无法确定原编码是何种编码,或者iconv转化后无法正常显示时才用mb_convert_encoding 函数.

from_encoding is specified by character code name before conversion. it can be array or string - comma separated enumerated list. if it is not specified, the internal encoding will be used.
/* auto detect encoding from jis, eucjp-win, sjis-win, then convert str to ucs-2le */
$str = mb_convert_encoding($str, “ucs-2le”, “jis, eucjp-win, sjis-win”);
/* “auto” is expanded to “ascii,jis,utf-8,euc-jp,sjis” */
$str = mb_convert_encoding($str, “euc-jp”, “auto”);

例子:
 

复制代码 代码示例:
<?php
$content = iconv(”gbk”, “utf-8″, $content);
$content = mb_convert_encoding($content, “utf-8″, “gbk”);

您可能感兴趣的文章:
PHP 数组字符集编码转换的函数
学习php字符串编码的转换与判断
php字符编码转换问题
php url编码与解码(加密/解密)
php中数组编码转换的方法
设置php页面编码的二种方法
php mb_convert_encoding文字编码转换函数
php判断字符编码的二个方法
php数组编码转换小例子
php iconv函数解决utf-8与gb2312编码转换问题

关键词: php编码  编码  编码转换   
[关闭]
~ ~