Home >Backend Development >PHP Tutorial >What should I do if PHP writes garbled characters to a txt file?
What should I do if PHP writes garbled characters to a txt file?
When performing file writing operations in PHP, sometimes Chinese characters may be garbled when written into a txt file. This problem is usually caused by inconsistent file encoding. In order to solve this problem, we need to specify the file encoding as UTF-8 when writing the file to ensure that Chinese characters are written into the txt file normally.
The following is a specific PHP code example that demonstrates how to correctly write Chinese content to a txt file and avoid garbled characters:
<?php // 定义要写入的中文内容 $content = "你好,世界!"; // 打开文件进行写入操作,注意指定编码为UTF-8 $fp = fopen('output.txt', 'w'); fwrite($fp, ""); // 添加BOM头,防止乱码 fwrite($fp, $content); fclose($fp); echo "写入成功!"; ?>
In the above code, first define the code to be written The input Chinese content is "Hello, world!", then open a file named output.txt through the fopen() function for writing, and use the fwrite() function to add a UTF-8 BOM before writing the content. header, this ensures that the written text content is stored in UTF-8 encoding, thereby avoiding garbled characters.
Hope the above code examples can help you solve the problem of garbled characters when PHP writes txt files, ensure that Chinese content is written correctly and avoid garbled characters.
The above is the detailed content of What should I do if PHP writes garbled characters to a txt file?. For more information, please follow other related articles on the PHP Chinese website!