i have multidimensional arrays generated by PHP with data from database ,but i have chars like \"č ć š đ ž\" and when i try to output that in json he just returns null , i d
Try 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;
}
I've found iconv
to be the best method of converting a character set to UTF-8. You can make use of PHP's array_walk_recursive
to work with multidimensional arrays:
$array = array(); // This is your multidimensional array
array_walk_recursive($array, function(&$value, $key) {
if (is_string($value)) {
$value = iconv('windows-1252', 'utf-8', $value);
}
});
You can change windows-1252
to whichever character set you're converting from.
if multidimensional array, then use foreach loop and use this line inside foreach suppose
foreach ($your_array as $line){
$line = array_map("utf8_decode", $line);
}
I met this problem as well and in 2016 you don't need to create a function, just use 'mb_convert_variables'
mb_convert_variables('UTF-8', 'original encode', array or object)
For anyone who meet this situation, too.
I don't use a function, I use the conversion in each assignment like:
$APP_UA_ID = utf8_encode($row['APP_UA_ID']);
$row = utf8_encode( $row );
convertUtf8ToHtml( $row );
$ROW_APP_DATA[] = $row;
See function below:
// converts a UTF8-string into HTML entities
// - $utf8: the UTF8-string to convert
// - $encodeTags: booloean. TRUE will convert '<' to '<'
// - return: returns the converted HTML-string
function convertUtf8ToHtml(&$utf8, $encodeTags = false )
{
if( !is_string( $utf8 ) || empty( $utf8 ))
{ return false; }
$result = '';
for ($i = 0; $i < strlen($utf8); $i++) {
$char = $utf8[$i];
$ascii = ord($char);
if ($ascii < 128) {
// one-byte character
$result .= ($encodeTags) ? htmlentities($char) : $char;
} else if ($ascii < 192) {
// non-utf8 character || not a start byte
} else if ($ascii < 224) {
// two-byte character
$result .= htmlentities(substr($utf8, $i, 2), ENT_QUOTES, 'UTF-8');
$i++;
} else if ($ascii < 240) {
// three-byte character
$ascii1 = ord($utf8[$i+1]);
$ascii2 = ord($utf8[$i+2]);
$unicode = (15 & $ascii) * 4096 +
(63 & $ascii1) * 64 +
(63 & $ascii2);
$result .= '&#$unicode;';
$i += 2;
} else if ($ascii < 248) {
// four-byte character
$ascii1 = ord($utf8[$i+1]);
$ascii2 = ord($utf8[$i+2]);
$ascii3 = ord($utf8[$i+3]);
$unicode = (15 & $ascii) * 262144 +
(63 & $ascii1) * 4096 +
(63 & $ascii2) * 64 +
(63 & $ascii3);
$result .= '&#$unicode;';
$i += 3;
}
}
$utf8 = $result;
return true;
}