Home  >  Article  >  Backend Development  >  Solution to garbled files read by PHP_PHP Tutorial

Solution to garbled files read by PHP_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 10:22:30719browse

Solution to garbled files read by PHP

PHP 5’s stream reading function seems to have a default encoding of UTF-8. In the past, file_get_contents() was used to read gb2312 directly in PHP 4 The encoding is normal, but when it reaches 5, it becomes garbled. The solution online says to use iconv() to transcode after crawling. After reading it, I felt something was wrong: one is that the iconv library may not have been compiled, and the bigger problem is that the encoding is related to the stream conversion (if iconv is used, PHP actually converts the code twice: stream-> UTF-8 -> GB2312): Isn’t this busy work in vain?

I carefully read the php documentation (I don’t know how everyone writes the code, but the documentation is very clear). It is mentioned above about fopen() and file_get_contents() that "the default is UTF-8, but the user You can specify a different encoding by creating a custom context or by changing the default using stream_default_encoding().). So I used stream_default_encoding('gb2312'); to test: But faintly, this function does not exist?! It seems that PHP 6 only supports it. However, there is no sure path, and there are also "user-defined context attributes" that can be used.

After reading the documentation more carefully, I finally solved this problem:

//Set the encoding format of the stream. This is the file stream (file). If it is network access, change the file to http

$opts = array('file' => array('encoding' => 'gb2312'));

 $ctxt = stream_context_create($opts);

file_get_contents(file name, FILE_TEXT, $ctxt);

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/848316.htmlTechArticleSolution to garbled files read by PHP. The stream reading function of PHP 5 seems to have a default encoding of UTF-8. Previously, In PHP 4, it is normal to read gb2312 encoding directly from file_get_contents(), but when it reaches PHP 5, it becomes garbled. ...
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