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;
}
Share... Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on TumblrShare on RedditEmail this to someone

11 Comments
Satheesh Thangavel
November 25, 2014 at 4:17 am

Thanks ! You saved me.

Arslan tabassum
December 12, 2014 at 10:13 am

use this line before fputcsv:
$line = array_map(“utf8_decode”, $line);

Andres
December 23, 2014 at 11:37 pm

Absolutely brilliant function for dealing with that json_parse() function that only accepts UTF-8, thank you very much.

mlc
January 8, 2015 at 4:26 pm

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.

Vinfo
August 16, 2015 at 8:25 pm

Is simple:
$utfEncoded = array_map(“utf8_encode”, $res );

Uki
September 17, 2015 at 3:16 am

Verrrryyyyy usefull … thank you.

Chris Johnson
October 24, 2015 at 8:51 pm

Thank you, worked perfectly for my French translations!

Cassio
December 4, 2015 at 1:20 pm

Thanks for your help with this function, worked for me !
🙂

Ricardo Borgneth
January 12, 2016 at 10:45 pm

Thank you. An excellent function.

Gabriel P. dos Santos
January 20, 2016 at 2:39 pm

It works perfectly , Thanks

Alexander
April 11, 2016 at 10:38 am

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 😉

Leave a Comment

Your email address will not be published. Required fields are marked *

Comment *
Your Name *
Your Email *
Website