为fread fwrite设置utf-8编码

beh*_*d n 4 php fopen fwrite fread

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

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

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

但是= =只有= utf-8字符显示"?" 要么 "[]" .我的编码Utf-8没有BOM,我使用它

header('Content-type: text/html; charset=UTF-8');
Run Code Online (Sandbox Code Playgroud)

还有这个 :

<meta http-equiv="content-type" content="text/html; charset=utf-8" />
Run Code Online (Sandbox Code Playgroud)

我在php.ini中的defult编码是utf-8但是还显示?.我在文件中看到chat.txt文件和字符,但是在文件中保存时和在页面中显示"?"时 而不是正确的.

Ven*_*enu 10

在阅读时使用此功能而不是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; 
} 
Run Code Online (Sandbox Code Playgroud)

来源
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>';
Run Code Online (Sandbox Code Playgroud)

试试这个

$content = iconv('windows-1250', 'utf-8', file_get_contents($fileName));
$bn = mb_split('||',$content);
foreach($bn as $b)
     echo $b.'<br>';
Run Code Online (Sandbox Code Playgroud)


Yag*_*iro 1

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