Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set text file encoding in PHP?

How can I set a text file ENCODING (for instance UTF-8) in PHP?

Let me show you my problem. This is my code:

<?php 
file_put_contents('test.txt', $data); // data is some non-English text with UTF-8 charset
?>

Output: اÙ!

fwrite() has the similar output.

But when I create the test.txt by notepad and set the charset UTF-8 the output is what I want. I wanna set the charset in the PHP file.

Now this is my question: How to set text file encoding by PHP?

like image 831
Programmer.zip Avatar asked Sep 28 '13 13:09

Programmer.zip


People also ask

Does PHP use UTF-8?

The utf8_encode() function is an inbuilt function in PHP which is used to encode an ISO-8859-1 string to UTF-8. Unicode has been developed to describe all possible characters of all languages and includes a lot of symbols with one unique number for each symbol/character.

How do I check if a string is UTF-8 in PHP?

$validUTF8 = mb_check_encoding($string, 'UTF-8'); Another function you can use is mb_detect_encoding [PHPManual]: $validUTF8 = ! (false === mb_detect_encoding($string, 'UTF-8', true));

What string encoding does PHP use?

The default source encoding used by PHP is ISO-8859-1 .


1 Answers

You may try this using mb_convert_encoding

$data = mb_convert_encoding($data, 'UTF-8', 'auto');
file_put_contents('test.txt', $data);

Also check iconv.

Update : (try this and find the right encoding for your text)

foreach(mb_list_encodings() as $chr){ 
    echo mb_convert_encoding($data, 'UTF-8', $chr)." : ".$chr."<br>";    
}

Also, try this on GitHub.

like image 162
The Alpha Avatar answered Sep 28 '22 07:09

The Alpha