How to write file in UTF-8 format?
Solution 1:
Add BOM: UTF-8
file_put_contents($myFile, "\xEF\xBB\xBF". $content);
Solution 2:
file_get_contents / file_put_contents will not magically convert encoding.
You have to convert the string explicitly; for example with iconv()
or mb_convert_encoding()
.
Try this:
$data = file_get_contents($npath);
$data = mb_convert_encoding($data, 'UTF-8', 'OLD-ENCODING');
file_put_contents('tempfolder/'.$a, $data);
Or alternatively, with PHP's stream filters:
$fd = fopen($file, 'r');
stream_filter_append($fd, 'convert.iconv.UTF-8/OLD-ENCODING');
stream_copy_to_stream($fd, fopen($output, 'w'));
Solution 3:
<?php function writeUTF8File($filename,$content) { $f=fopen($filename,"w"); # Now UTF-8 - Add byte order mark fwrite($f, pack("CCC",0xef,0xbb,0xbf)); fwrite($f,$content); fclose($f); } ?>