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.
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:
utf8_encode($str)
before saving. fwrite($f, "\\xEF\\xBB\\xBF")
iconv()
recode L1..UTF8 script.php
what program are you using to "open" the file? that program could be the problem.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.