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

时间:2011-02-03 06:06:52

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

提前致谢。

3 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:2)

你用什么程序来“打开”文件?该计划可能是问题所在。

答案 2 :(得分:0)

首先,在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 ++)来执行此操作。