0

我有一个 UCS-2 文本文件。现在,我想将此文本文件作为 UTF-8 字符串读取。我已经使用此代码来执行此操作。

my_code.php

<?php

error_reporting(0);        
header('Content-Type: text/html; charset=utf-8');

echo '<form enctype="multipart/form-data" method="post"><p><input type="file" name="my_file" />&nbsp;<input type="submit" value="+" /><hr />';

$my_str = file_get_contents(($_FILES['my_file']['tmp_name']));
echo $my_str;

?>

viet_test.txt

"Vietnamese" is "Tiếng Việt".

但是,它返回错误��"Vietnamese" is "Ti�ng Vi�t".。这就是我想要的:("Vietnamese" is "Tiếng Việt"在 UTF-8 中)。

你能告诉我:“我的代码有什么问题?以及,如何解决它?”。


对不起,我对 PHP 不是很专业。

4

1 回答 1

1

您无法“以 UTF-8 格式”读取文件。它包含 UCS-2,因此阅读它您将阅读 UCS-2 字符串。但是,您可以读取的 UCS-2 字符串转换为 UTF-8:

$my_str = file_get_contents($_FILES['my_file']['tmp_name']);
$my_str = mb_convert_encoding($my_str, 'UTF-8', 'UCS-2');
echo $my_str;

请注意,您可能必须使用UCS-2BEorUCS-2LE明确。
如果仍然返回“无”,那么您遇到的问题与编码有关。

于 2015-09-04T13:13:57.630 回答