set utf-8 encoding for fread fwrite

behzad n picture behzad n · May 18, 2012 · Viewed 63k times · Source

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

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 .

Answer

Venu picture Venu · May 18, 2012

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

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

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>';