search
Homephp教程php手册php数组编码转换示例详解

因为一些特殊字符的显示效果的原因不得不把习惯的utf-8工程改成了GBK,由于使用了ajax技术,又涉及到了老问题——编码转换。一些表单验证需要返回json数据,php的json_encode函数只支持utf-8编码,无奈只得iconv了,需要达到的效果是GBK数组转换成utf-8数组传给json_encode函数。

最开始的思路,将数组序列化后用iconv函数转换编码,之后再反序列化,代码如下:

复制代码 代码如下:


unserialize(iconv('gbk','utf-8',serialize($array))); 

得到的结果是空白,后来想起来配置文件里设置了默认编码 ini_set('default_charset', 'gbk');   这样用gbk反序列化utf-8的字符串肯定不好用了,此处在序列化和反序列化之间加个ini_set('default_charset', 'utf-8'); 应该也是可以的,但这么弄总觉得有点别扭,因为是全局的编码设置,很容易导致其他地方的编码问题,比如数据库操作。那么换个思路,用构建数组原型的序列化方法,借助var_export函数,最终函数如下:

复制代码 代码如下:


function array_iconv($in_charset,$out_charset,$arr){ 
        return eval('return '.iconv($in_charset,$out_charset,var_export($arr,true).';')); 
}

原理很简单 var_export设置第二个参数为true,返回数组原型字符串,将字符串转换为utf-8编码,之后再用eval来执行返回(类似匿名函数?),至此完美解决问题。

后续:后来在网上搜了下资料,看有没有更好的方法,找到的都大同小异,都是利用递归调用iconv的方式,如果数组元素过多或者维数多一些,性能上肯定不怎么样了,更好的是原生代码的方式,不需要考虑是N维数组还是关联数组,一切都已经自动完成,保证数组转换前后数据一致。从代码的长短以及循环和原生方法的比较上,相信大家已经有了选择。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version