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?
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.
$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));
The default source encoding used by PHP is ISO-8859-1 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With