php 5的流读取函数默认编码是UTF-8,之前在php 4里直接file_get_contents()读取gb2312编码的正常,但是到了php 5之后就出现乱码现象了,下面讲述一下具体的解决方案。
大家可以仔细看一下php开发文档,上面记录的十分清楚,关于fopen()及file_get_contents()都提到了“默认是UTF-8,但是用户可以用stream_default_encoding()或者用户自定义上下文属性改变编码。
英文记录如下:
If unicode semantics are enabled, the default encoding of the read data is UTF-8. You can specify a different encoding by creating a custom context or by changing the default using stream_default_encoding()。
于是用stream_default_encoding('gb2312′);注意在php 6之后才支持使用faint函数,所以可以用“用户自定义上下文属性”来实现。
具体解决方式代码如下:
//设置流的编码格式文件流(file)网络访问file改成http
$opts = array('file' => array('encoding' => 'gb2312')); $ctxt = stream_context_create($opts); file_get_contents(文件名, FILE_TEXT, $ctxt);