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

Here is my code:

<?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
?>

To the screen, the output is:

óéü

When I open the file I get:

óéü

I am trying to save large amounts of data using fwrite, but the characters are not encoding correctly at the point of file save.

Thanks in advance.

what program are you using to "open" the file? that program could be the problem.

fwrite stores strings binary. It does not do any charset conversion. It's more likely that your PHP script is in a wrong charset, and thus the original "óéü" string. Show us the bin2hex($str) and bin2hex(file_get_contents('demo.txt')) if you can't debug it yourself.

There are some generic options to solve such problems:

  • Using utf8_encode($str) before saving.
  • Writing the UTF-8 BOM into the output file first fwrite($f, "\xEF\xBB\xBF")
  • correct conversion with iconv()
  • or adapting the php script itself with recode L1..UTF8 script.php

First, insert the utf_encode inside the fwrite, like this:

<?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
?> 

Next, remember to save your PHP script with UTF-8 without BOM encoding. Use any advanced code editor like Notepad++ to do this.