php 为 fread fwrite 设置 utf-8 编码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10653735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:43:44  来源:igfitidea点击:

set utf-8 encoding for fread fwrite

phpfopenfwritefread

提问by behzad n

hi i use this code read and write text in file .

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

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

and

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

but in =ie only= utf-8 character show "?" or "[]" . my encoding Utf-8 Without BOM and i use this

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

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

and This :

和这个 :

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

my defult encoding in php.ini is utf-8 but yet show ? . i see chat.txt file and character right in file but when with ie save in file And when show in page show "?" instead of right .

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

回答by Venu

Use this function instead of fopen while reading but not while writing

在读取时使用此函数而不是 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; 
} 

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

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

In your case

在你的情况下

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

Try this

尝试这个

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

回答by Yago Riveiro

The TXT was saved with utf8 encode? You need to ensure that the TXT codification is utf-8, otherwise you will need use utf8_encode function

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

回答by EmmanuelG

You can encode the string you are outputting, $bn in this case, using utf8_encode() like this:

您可以像这样使用 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>';

Try that and see if it's still wierd.

尝试一下,看看它是否仍然很奇怪。