My code:
$filesss = glob('./pic/*.jpg');
print_r($filesss);When running the program on a Windows environment, the output file name displays as garbled text.
Invalid character display reason:
On Windows, PHP uses the system's default encoding by default when processing file names; this can cause file names containing Chinese characters or other non-ASCII characters to be displayed as garbled text during output.
Solution:
Use iconv() The function converts the file name into an appropriate encoding before outputting it.
Final code:
$filesss = glob('./pic/*.jpg');
// 遍历文件数组,并使用 iconv 函数转换编码
foreach ($filesss as $file) {
// 将文件名从系统默认编码转换为 UTF-8
$file_utf8 = iconv("CP936", "UTF-8", $file); // CP936 是 Windows 下的默认中文编码
// 输出转换后的文件名
echo $file_utf8 . "\n";
}iconv("CP936", "UTF-8", $file)It converts the Windows default Chinese character encoding (CP936, also known as GBK) to UTF-8 encoding, ensuring that the file names are displayed correctly.
If the original encoding of the file name is not CP936 but another encoding (e.g., UTF-8), you should adjust it accordingly based on the actual situation. iconv() Parameters in a function.