Solve the problem that file_get_contents cannot open a Chinese file name when encountering a problem _ PHP Tutorial

Source: Internet
Author: User
Solve the problem that the Chinese file name cannot be opened when file_get_contents encounters. Use file_get_contents to open a file or collect a remote server file. if the file name or url contains Chinese characters, the failedtoopenstream: Lnvalidargumentin error may occur. Today, a file is opened using file_get_contents or a remote server file is collected. if the file name or url contains Chinese characters, a failed to open stream: Lnvalid argument in error occurs.

Today, we encountered a very difficult problem. the customer used ftp to upload a file to the server, but it was not recognized by the program. after checking the code, no problem was found. Finally, the repeat process found that the files uploaded by the customer were named in Chinese. as a result, the test showed that the file_get_contents function does not support Chinese file names.

The original code is as follows:

Using filename='ha.txt ';

Echo file_get_contents ('./'. $ filename );

Display results after execution:

Tragedy begins.

After that, I tried a lot of judgment methods to check whether the encoding problem, file encoding, and code encoding are all correct.

After that, I found the relevant information but did not find it. so google found that someone encountered this problem, saying it was a problem with system encoding, and began to transcode the file name.

The file uses UTF-8 encoding, but the system defaults to gbk. Therefore, convert the file name to gbk before reading it.

Using filename='ha.txt ';

$ Filename = iconv ('utf-8', 'gb2312', $ filename );

// Echo file_get_contents (mb_convert_encoding ('./.txt', 'gbk', 'utf-8'); (another method)

Echo file_get_contents ('./'. $ filename );


Test results:

Read successful.

OK.

Failed to open stream: Lnvalid argument in error. Today I met...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.