I want to write to a text file. When I use substr_replace in php the encoding changes. It doesn't print Greek Characters correctly. If I don't everything is fine. Any suggestions?
<?php
$file = "test.txt";
$writeFile = fopen($file, "w+");//read/write
$myarray = array("δφδφ","δφδσφδσ","δφδφδ");
$myarray[0] = substr_replace($myarray[0],"ε", 0,1);
foreach ($myarray as $data){
fwrite($writeFile, $data."\n");
}
?>
OUTCOME
ε�φδφ
δφδσφδσ
δφδφδ
OUTCOME WITH NO substr_replace
δφδφ
δφδσφδσ
δφδφδ
Assuming you're encoding the Greek in a multi-byte encoding (like UTF-8), this won't work because the core PHP string functions, including
substr_replace
, are not multi-byte aware. They treat one character as equal to one byte, which means you'll end up slicing multi-byte characters in half if you only replace their first byte. You need to use a more manual approach involving a multi-byte aware string function likemb_substr
:The comment @arma links to in the comments wraps that functionality in a function.
Try this version:
You could try using the
mb_convert_encoding()
function to set the correct encoding.You can use these two functions:
from shkspr.mobi
From GitHub
I tried both and both work well