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?


ANSWERS:


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).

file_put_contents("file.txt", "\xEF\xBB\xBF" . $data);

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.


Try:

file_put_contents('test.txt', utf8_encode($data)); 

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.

<?php
function utf8_string_encode(&$array){
    $myencode = function(&$value,&$key){
        if(is_string($value)){
            $value = utf8_encode($value);
        } 
        if(is_string($key)){
            $key = utf8_encode($key);
        }
        if(is_array($value)){
            utf8_string_encode($value);
        }
    };
    array_walk($array,$func);
    return $array;
}
?>


 MORE:


 ? Transferring extended ascii characters with unknown encoding to a Twisted XMLRPC from C#
 ? Transferring extended ascii characters with unknown encoding to a Twisted XMLRPC from C#
 ? Transferring extended ascii characters with unknown encoding to a Twisted XMLRPC from C#
 ? how to: Twisted privmsg to accept non-ascii strings
 ? How to send XML-RPC request from XML-RPC callback in twisted
 ? Allowing any ASCII character transmitted in string with xmlrpc
 ? Rails 4: incompatible character encodings: UTF-8 and ASCII-8BIT
 ? twisted xmlrpc and numpy float 64 exception
 ? GetPrivateProfileString Oddity
 ? GetPrivateProfileString Oddity