Convert php array to UTF8 recursively
This simple php function converts recursively all values of an array to UTF8.
The function mb_detect_encoding (line 4) checks if the value already is in UTF8, this way it will not reconvert.
1 2 3 4 5 6 7 8 9 10 | function utf8_converter($array) { array_walk_recursive($array, function(&$item, $key){ if(!mb_detect_encoding($item, 'utf-8', true)){ $item = utf8_encode($item); } }); return $array; } |
11 Comments
Thanks ! You saved me.
use this line before fputcsv:
$line = array_map(“utf8_decode”, $line);
Absolutely brilliant function for dealing with that json_parse() function that only accepts UTF-8, thank you very much.
From the PHP manual:
utf8_encode — Encodes an ISO-8859-1 string to UTF-8
cool function but do know that the input file should be ISO-8859-1 for this to work. Why not use
$item = mb_convert_encoding($item, ‘UTF-8);
so that the USO-8859-1 depenency is gone…?
mlc.
Is simple:
$utfEncoded = array_map(“utf8_encode”, $res );
Verrrryyyyy usefull … thank you.
Thank you, worked perfectly for my French translations!
Thanks for your help with this function, worked for me !
🙂
Thank you. An excellent function.
It works perfectly , Thanks
Thanks! Helped me a lot! 😀
Just a question: why not simply:
if(mb_detect_encoding($item, ‘utf-8’, false)) { … }
should do exactly the same but it’s easier to read since there is no double negation 😉