How to convert php array to utf8?
Asked Answered
C

13

23

I have an array:

require_once ('config.php');
require_once ('php/Db.class.php');
require_once ('php/Top.class.php');

echo "db";

$db = new Db(DB_CUSTOM);
$db->connect();

$res = $db->getResult("select first 1 * from reklamacje");

print_r($res);

I want to convert it from windows-1250 to utf-8, because I have chars like �

Best.

Canon answered 22/5, 2013 at 9:26 Comment(4)
You can use string utf8_encode( string $data ) function.Andress
What if you originally store/retrieve data in a correct encoding? It makes sense to fix the root of the issue not the consequencesGate
$res = array_map('utf8_encode', $res);.Pisistratus
@Pisistratus this wont work with a multidimensional array.Egin
B
48
$utfEncodedArray = array_map("utf8_encode", $inputArray );

Does the job and returns a serialized array with numeric keys (not an assoc).

Bulbul answered 5/11, 2013 at 21:9 Comment(3)
Works very well for me! :)Broussard
utf8_encode() expects parameter 1 to be string, array given; PHP 7.4.4.Continual
Just tested it with 7.4.3 - no complaints - are you sure your input array doesn't contain any array elements? This solution is not recursive!Bulbul
S
19
array_walk(
    $myArray,
    function (&$entry) {
        $entry = iconv('Windows-1250', 'UTF-8', $entry);
    }
);
Salamander answered 22/5, 2013 at 9:31 Comment(1)
looks nice, but what do I give as second parameter when I call it?Charade
H
17

In case of a PDO connection, the following might help, but the database should be in UTF-8:

//Connect
$db = new PDO(
    'mysql:host=localhost;dbname=database_name;', 'dbuser', 'dbpassword',
    array('charset'=>'utf8')
);
$db->query("SET CHARACTER SET utf8");
Howsoever answered 25/12, 2014 at 20:38 Comment(0)
R
16

There is an easy way

array_walk_recursive(
  $array,
  function (&$entry) {
    $entry = mb_convert_encoding(
        $entry,
        'UTF-8',
        'WINDOWS-1250'
    );
  }
);
Ripple answered 9/9, 2016 at 6:44 Comment(1)
The 3rd parameter of mb_convert_encoding() should be specified otherwise it will take the value of mbstring.internal_encoding or default_charset (php.ini) which may not be desired encoding.Centroclinal
P
11

You can use something like this:

<?php
array_walk_recursive(
$array, function (&$value)
{
 $value = htmlspecialchars(html_entity_decode($value, ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8');
}
);
?>
Protochordate answered 12/9, 2013 at 12:31 Comment(0)
C
9

You can send the array to this function:

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;
}

It works for me.

Confirmand answered 22/7, 2020 at 17:57 Comment(0)
C
2

Previous answer doesn't work for me :( But it's OK like that :)

         $data = json_decode(
              iconv(
                  mb_detect_encoding($data, mb_detect_order(), true),
                  'CP1252',
                  json_encode($data)
                )
              , true)
Clemmieclemmons answered 5/11, 2019 at 22:15 Comment(0)
A
0

You can use string utf8_encode( string $data ) function to accomplish what you want. It is for a single string. You can write your own function using which you can convert an array with the help of utf8_encode function.

Andress answered 22/5, 2013 at 9:30 Comment(1)
Have you checked what's the input encoding used for utf8_encode?Gate
K
0

Due to this article is a good SEO site, so I suggest to use build-in function "mb_convert_variables" to solve this problem. It works with simple syntax.

mb_convert_variables('utf-8', 'original encode', array/object)

Karykaryl answered 15/1, 2016 at 2:16 Comment(0)
A
0

A more general function to encode an array is:

/**
 * also for multidemensional arrays
 *
 * @param array $array
 * @param string $sourceEncoding
 * @param string $destinationEncoding
 *
 * @return array
 */
function encodeArray(array $array, string $sourceEncoding, string $destinationEncoding = 'UTF-8'): array
{
    if($sourceEncoding === $destinationEncoding){
        return $array;
    }

    array_walk_recursive($array,
        function(&$array) use ($sourceEncoding, $destinationEncoding) {
            $array = mb_convert_encoding($array, $destinationEncoding, $sourceEncoding);
        }
    );

    return $array;
}
Alina answered 12/2, 2018 at 8:59 Comment(0)
D
0

The simple way tha works is:

array_map(callable $callback, array $array1, array $... = ?): array

//Example #1 Example of the function array_map()

<?php
function cube($n)
{
    return($n * $n * $n);
}

$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
?>

The Output of $b is:

Array
(
    [0] => 1
    [1] => 8
    [2] => 27
    [3] => 64
    [4] => 125
)

For futher details src -> PHP: array_map - Manual

Deathblow answered 23/9, 2021 at 15:38 Comment(0)
T
0
<?php

$search = [
    "\x5A\x6F\xEB"
];

$searchRes = array_map('utf8_encode', $search);

var_dump($searchRes);

echo PHP_EOL.PHP_EOL;

$searchRes = array_map(fn($item) => mb_convert_encoding($item, 'UTF-8', 'ISO-8859-1'), $search);

var_dump($searchRes);

PHP Sandbox

Trigger answered 9/7 at 9:15 Comment(0)
M
-3

Instead of using recursion to deal with multi-dimensional arrays, which can be slow, you can do the following:

$res = json_decode(
    json_encode(
        iconv(
            mb_detect_encoding($res, mb_detect_order(), true),
            'UTF-8',
            $res
        )
    ),
    true
);

This will convert any character set to UTF8 and also preserve keys in your array. So instead of "lazy" converting each row using array_walk, you could do the whole result set in one go.

Muttonhead answered 16/8, 2014 at 23:26 Comment(1)
mb_detect_encoding() expects parameter 1 to be string, $res is NOT a string.Ilan

© 2022 - 2024 — McMap. All rights reserved.