Reputation: 2811
To write data to file encoded in UTF-8 (with BOM):
function writeStringToFile($file, $string){
$f=fopen($file, "wb");
$string="\xEF\xBB\xBF".$string; // UTF-8
fputs($f, $string);
fclose($f);
}
How do I write data encoded in UTF-8 without BOM?
A screenshot from notepad++ with encodings:
Upvotes: 0
Views: 4315
Reputation: 7010
The string "\xEF\xBB\xBF"
match the «UTF-8 with BOM» format.
If you have a string with this format and want to write it in a file with a «simple» UTF-8, you have to remove theses characters. This can be done in various way, for example with preg_replace
:
function writeStringToFileUTF8($file, $string){
$string = preg_replace("`\xEF\xBB\xBF`", "", $string);
// this is equivalent as fopen(w)/fputs()/fclose()
file_put_contents($file, $string);
}
Upvotes: 0
Reputation: 652
The only way I found is removing the BOM after creating the file.
<?php
// change the pathname to your target file which you want to remove the BOM
$pathname = "./test.txt";
$file_handler = fopen($pathname, "r");
$contents = fread($file_handler, filesize($pathname));
fclose($file_handler);
for ($i = 0; $i < 3; $i++){
$bytes[$i] = ord(substr($contents, $i, 1));
}
if ($bytes[0] == 0xef && $bytes[1] == 0xbb && $bytes[2] == 0xbf){
$file_handler = fopen($pathname, "w");
fwrite($file_handler, substr($contents, 3));
fclose($file_handler);
printf("%s BOM removed.
\n", $pathname);
}
?>
Upvotes: 0
Reputation: 1029
function writeStringToFile($file, $string){
$f=fopen($file, "wb");
// $file="\xEF\xBB\xBF".$file; // UTF-8 <-- this is UTF8 BOM
fputs($f, $string);
fclose($f);
}
Upvotes: 1