【php基础】iconv 与 mb_convert_string 字符串转换

来源:互联网 发布:个体户域名备案 编辑:程序博客网 时间:2024/05/22 11:37

最近也一直在和字符串转换打交道,比较常用到的就是这两个php自带的字符串转换.那么接下来我会以一些场景来使用这两个字符串编码转换函数


使用场景:
请求:ajax POST请求
服务器编码 GBK
页面编码 GBK

问题:因为ajax请求发出的数据都是utf-8格式的编码,因此我们必须要将utf-8编码的数据进行一个转换

解决办法1: 使用iconv

<?php$postStr = file_get_contents("file://input"); // 将post的数据以字符流的形式读取$inCharset = "UTF-8";$outCharset = "GBK";$postStr = iconv($inCharset,$outCharset,$postStr);// 将字符串转换为$_POST形式的数组parse_str($postStr,$_post);

解决办法2: 使用mb_convert_encode()

<?php$postStr = file_get_contents("file://input"); // 将post的数据以字符流的形式读取$inCharset = "UTF-8";$outCharset = "GBK";$postStr = mb_convert_encode($postStr,$outCharset,$inCharset);// 将字符串转换为$_POST形式的数组parse_str($postStr,$_post);

以上两种方法均可以进行字符串转码,然而有一点需要注意,如果将转换好的字符串转回去,切不可两种方法混用.否则中文字符可能会出现阶段的问题。

示例:

<?php$postStr = file_get_contents("file://input"); // 将post的数据以字符流的形式读取$inCharset = "UTF-8";$outCharset = "GBK";$postStr = mb_convert_encode($postStr,$outCharset,$inCharset);// 转换为原来的字符串$postStr = iconv($outCharset,$inCharset."//IGNORE",$postStr);// 如果源 $postStr为 UTF-8'我是谁?'// 那么新的 $postStr'?' ,如果不加 "//IGNORE" 结尾 则会跑出一个异常

因此千万不要嵌套两个方法进行相互转换。

0 0