How to set text file encoding in PHP?

2019-03-15 17:47发布

问题:

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?

回答1:

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


回答2:

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.



回答3:

Try:

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


回答4:

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;
}
?>