【问题标题】:In PHP, when I use fwrite, I don't get the correct character set在 PHP 中,当我使用 fwrite 时,我没有得到正确的字符集
【发布时间】:2011-02-03 06:06:51
【问题描述】:

这是我的代码:

<?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 保存大量数据,但在文件保存时字符编码不正确。

提前致谢。

【问题讨论】:

  • 也许可以试试this suggestion
  • 抱歉耽搁了这么久。事实证明,查看器是问题所在。我有几个文本编辑器,并且,根据我使用的哪个,我会得到 UTF-8 字符集还是没有!我最终将 Coda 用于所有事情,并且没有遇到任何其他问题。

标签: php file encoding


【解决方案1】:

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脚本本身

【讨论】:

    【解决方案2】:

    您使用什么程序来“打开”文件?那个程序可能是问题所在。

    【讨论】:

      【解决方案3】:

      首先,在 fwrite 中插入 utf_encode,如下所示:

      <?php
      
      $fName = "demo.txt";
      $str   = "óé";
      fid   = fopen($fName, 'wb') or die("can't open file"); // Open file
      
      fwrite($fid, utf_encode($str)); // Write to file
      fclose($fid);         // Close file
      ?> 
      

      接下来,请记住使用UTF-8 without BOM 编码保存您的 PHP 脚本。使用任何高级代码编辑器(如 Notepad++)来执行此操作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-23
        相关资源
        最近更新 更多