Heim  >  Artikel  >  Backend-Entwicklung  >  PHP 读取文件乱码的解决方法_PHP教程

PHP 读取文件乱码的解决方法_PHP教程

WBOY
WBOYOriginal
2016-07-21 14:54:531046Durchsuche

php 5的流读取函数好像默认编码是UTF-8,以前在php 4里直接file_get_contents()读取gb2312编码的正常,到了5就乱码了。网上的解决办法说抓取后用iconv()转码。看后我就觉 得不对劲:一个是不一定编译了iconv库,更大的问题是编码都跟流转换的时候有关(如果用了iconv实际上php转了两次码:流 -> UTF-8 -> GB2312):这不是白忙乎了吗?

仔细看了下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′);测试:但是 faint的是,这个函数不存在?!似乎php 6才支持。不过天无绝人之路,还有“用户自定义上下文属性”可以用。

经过更仔细的看文档,最后解决了这个问题:

//设置流的编码格式,这是文件流(file),如果是网络访问,file改成http
$opts = array('file' => array('encoding' => 'gb2312'));
$ctxt = stream_context_create($opts);
file_get_contents(文件名, FILE_TEXT, $ctxt);

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/364477.htmlTechArticlephp 5的流读取函数好像默认编码是UTF-8,以前在php 4里直接file_get_contents()读取gb2312编码的正常,到了5就乱码了。网上的解决办法说抓取后用...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn