Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write file in UTF-8 format?

I have bunch of files that are not in UTF-8 encoding and I'm converting a site to UTF-8 encoding.

I'm using simple script for files that I want to save in UTF-8, but the files are saved in old encoding:

header('Content-type: text/html; charset=utf-8'); mb_internal_encoding('UTF-8'); $fpath = "folder"; $d = dir($fpath); while (False !== ($a = $d->read())) {     if ($a != '.' and $a != '..')     {         $npath = $fpath . '/' . $a;          $data = file_get_contents($npath);          file_put_contents('tempfolder/' . $a, $data);     } } 

How can I save files in UTF-8 encoding?

like image 665
Starmaster Avatar asked Jan 29 '11 21:01

Starmaster


People also ask

How do I make sure a file is UTF-8?

Open the file in Notepad. Click 'Save As...'. In the 'Encoding:' combo box you will see the current file format. Yes, I opened the file in notepad and selected the UTF-8 format and saved it.

How do I change my encoding to UTF-8?

UTF-8 Encoding in Notepad (Windows)Click File in the top-left corner of your screen. In the dialog which appears, select the following options: In the "Save as type" drop-down, select All Files. In the "Encoding" drop-down, select UTF-8.

How do I convert a CSV file to UTF-8?

Navigate to File > Export To > CSV. Under Advanced Options, select Unicode(UTF-8) option for Text Encoding. Click Next. Enter the name of the file and click Export to save your file with the UTF-8 encoding.


2 Answers

Add BOM: UTF-8

file_put_contents($myFile, "\xEF\xBB\xBF".  $content);  
like image 77
user956584 Avatar answered Sep 29 '22 10:09

user956584


file_get_contents() and 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')); 
like image 39
Arnaud Le Blanc Avatar answered Sep 29 '22 10:09

Arnaud Le Blanc