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?
You may try this using mb_convert_encoding
Also check iconv.
Update : (try this and find the right encoding for your text)
Also, try this on GitHub.
PHP does not apply an encoding when storing text in a file: it stores data exactly as it is laid out in the string.
You mention that you have problems opening the file in
notepad.exe
. That text editor is not very good at guessing the encoding of the file you are opening; if the text is encoded in UTF-8 you must choose to open it as UTF-8. Use another text editor if possible. Notepad++ is a popular replacement.If you must use
notepad.exe
, as a last resort, write a Byte Order Mark to the file before you write anything else; this will make it recognize the file as UTF-8 while potentially making the file unusable for other purposes (see the Wikipedia article for details).Try:
You can create a function which converts a string array into a utf8 encoded string array and another to decode and write to a notepad file for you.