How to set text file encoding in PHP?

2019-03-15 18:00发布

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?

4条回答
狗以群分
2楼-- · 2019-03-15 18:06

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.

查看更多
Juvenile、少年°
3楼-- · 2019-03-15 18:11

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);
查看更多
Juvenile、少年°
4楼-- · 2019-03-15 18:23

Try:

file_put_contents('test.txt', utf8_encode($data)); 
查看更多
Juvenile、少年°
5楼-- · 2019-03-15 18:23

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;
}
?>
查看更多
登录 后发表回答