6

嗨,我使用此代码在文件中读取和写入文本。

$d = fopen("chat.txt", "r");
 $content=fread($d,filesize('chat.txt'));
 $bn=explode('||',$content);
 foreach($bn as $bn)
 echo $bn.'<br>';

$d = fopen("chat.txt", "a");
 $c=$_GET['c'];
 if($c=='') die();
 fwrite($d,$c.'||');
 fclose($d);

但在 =ie only= utf-8 字符显示“?” 或者 ”[]” 。我的编码 Utf-8 没有 BOM,我用这个

header('Content-type: text/html; charset=UTF-8');

和这个 :

<meta http-equiv="content-type" content="text/html; charset=utf-8" />

我在 php.ini 中的默认编码是 utf-8 但还显示?. 我在文件中看到了 chat.txt 文件和字符,但是当使用 ie 保存在文件中并且在页面中显示时显示“?” 而不是对。

4

3 回答 3

13

读取时使用此函数而不是 fopen,但写入时不使用

function utf8_fopen_read($fileName) { 
    $fc = iconv('windows-1250', 'utf-8', file_get_contents($fileName)); 
    $handle=fopen("php://memory", "rw"); 
    fwrite($handle, $fc); 
    fseek($handle, 0); 
    return $handle; 
} 

来源
http://www.php.net/manual/en/function.fopen.php#104325

在你的情况下

$d = utf8_fopen_read("chat.txt", "r");
 $content=fread($d,filesize('chat.txt'));
 $bn=explode('||',$content);
 foreach($bn as $bn)
 echo $bn.'<br>';

尝试这个

$content = iconv('windows-1250', 'utf-8', file_get_contents($fileName));
$bn = mb_split('||',$content);
foreach($bn as $b)
     echo $b.'<br>';
于 2012-05-18T13:56:02.297 回答
1

TXT 是用 utf8 编码保存的吗?您需要确保 TXT 编码为 utf-8,否则您将需要使用 utf8_encode 函数

于 2012-05-18T13:49:19.357 回答
1

您可以像这样使用 utf8_encode() 对要输出的字符串进行编码,在本例中为 $bn:

$d = fopen("chat.txt", "r");
$content=fread($d,filesize('chat.txt'));
$bn=explode('||',$content);
foreach($bn as $bn)
echo utf8_encode($bn).'<br>';

试试看它是否仍然很奇怪。

于 2012-05-18T13:49:43.197 回答