php - 在 PHP 中,当我使用 fwrite 时,我没有得到正确的字符集

标签 php file encoding

这是我的代码:

<?php
  header("Content-Type: text/html; charset=UTF-8");
  header("Content-Type: application/x-javascript; charset=UTF-8");

  $fName = "demo.txt";
  $str   = "óé";
  fid   = fopen($fName, 'wb') or die("can't open file"); // Open file

  fwrite($fid, $str); // Write to file
  fclose($fid);         // Close file
?>

到屏幕上,输出是:

óéü

当我打开文件时,我得到:

óéü

我尝试使用 fwrite 保存大量数据,但在文件保存时字符编码不正确。

提前致谢。

最佳答案

fwrite 存储二进制字符串。它不进行任何字符集转换。 更有可能的是,您的 PHP 脚本的字符集错误,因此原始的 "óéü" 字符串也错误。如果您无法自行调试,请向我们展示 bin2hex($str)bin2hex(file_get_contents('demo.txt'))

有一些通用选项可以解决此类问题:

  • 保存前使用 utf8_encode($str)
  • 首先将 UTF-8 BOM 写入输出文件fwrite($f, "\xEF\xBB\xBF")
  • 使用 iconv() 进行正确转换
  • 或使用 recode L1..UTF8 script.php 调整 php 脚本本身

关于php - 在 PHP 中,当我使用 fwrite 时,我没有得到正确的字符集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4883035/

相关文章:

linux - 查找文件名中数字大于的文件

ruby - 如何确定Ruby中字符串的编码

javascript - 限制可以访问页面的查看者数量

php - 对表 1 的请求中表 2 中的用户进行计数

java - 在Java中反转大量文本文件

java - 为什么说: CharacterStream classes are used to perform the input/output for the 16-bit Unicode characters?

encoding - 如何使用 X264 对一系列 .dpx 文件进行编码

php - 将 mySQL 结果显示为水平图 block

PHP MySQL奇怪的更新问题

oracle - 清除和删除文件之间的区别?