2015-09-04 89 views
0

我有一個UCS-2文本文件。現在,我想以UTF-8字符串的形式讀取此文本文件。我已經使用這個代碼來做到這一點。如何在PHP中將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".。有什麼我looing:"Vietnamese" is "Tiếng Việt"(在UTF-8)。

你能告訴我:「我的代碼出了什麼問題?以及如何解決它?」。


我很抱歉,我不是很專業的PHP。

回答

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明確。
如果這仍然返回「什麼都沒有」,你有一個不同的問題比編碼做任何事情。

+0

如果你必須「確定」它,你已經處於一種不舒服的狀態。你應該知道什麼是編碼。你可以使用'mb_detect_encoding($ my_str,array('UCS-2LE','UCS2-BE','UCS-2')​​)''。 – deceze

相關問題