【问题标题】:How to read an UCS-2 text-file as an UTF-8 string, in PHP?如何在 PHP 中将 UCS-2 文本文件读取为 UTF-8 字符串?
【发布时间】:2015-09-04 12:57:24
【问题描述】:

我有一个 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不是很专业。

【问题讨论】:

    标签: php string utf-8 ucs2


    【解决方案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-2BEUCS-2LE
    如果仍然返回“nothing”,那么您遇到的问题与编码有关。

    【讨论】:

    • 如果你必须“确定”它,你已经处于一个不舒服的境地。你应该知道什么编码。你可以使用mb_detect_encoding($my_str, array('UCS-2LE', 'UCS2-BE', 'UCS-2'))
    猜你喜欢
    • 2016-05-03
    • 2010-10-29
    • 2016-08-14
    • 2014-09-14
    • 1970-01-01
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    • 2011-10-23
    相关资源
    最近更新 更多