Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set utf-8 encoding for fread fwrite

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 .

like image 632
behzad n Avatar asked May 18 '12 13:05

behzad n


3 Answers

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>';
like image 156
Venu Avatar answered Oct 28 '22 03:10

Venu


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

like image 31
Yago Riveiro Avatar answered Oct 28 '22 04:10

Yago Riveiro


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

$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.

like image 26
EmmanuelG Avatar answered Oct 28 '22 04:10

EmmanuelG