set utf-8 encoding for fread fwrite
Asked Answered
C

3

7

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 .

Caterer answered 18/5, 2012 at 13:39 Comment(2)
For each ($bn as $bn) overwrites $bn, so it will only execute it like a heigharcyVagina
change bn with bn1 but no diferentCaterer
P
15

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>';
Patience answered 18/5, 2012 at 13:56 Comment(1)
No more rolling debug session... Sorry.Canasta
M
1

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

Milore answered 18/5, 2012 at 13:49 Comment(3)
i use utf8 not work and change to ansi an use utf8_encode and yet not workCaterer
I think your problem is that you data was re-encoded in utf8 again, try to use utf8_decode instead of utf8_encode. Sometimes this happensMilore
if i dont use utf8 show like this [pic] (up.vatandownload.com/images/04pbtwwrpy6vi7xk5u4.jpg)Caterer
L
1

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.

Lintel answered 18/5, 2012 at 13:49 Comment(1)
If you are seeing this sort of thing then the most likely fix would be to make sure the contents of the file you are writing is utf8 encoded. Also, check out the answer above by @Venu. Character encoding issues are always a hassle to fix. Good luck.Lintel

© 2022 - 2024 — McMap. All rights reserved.