json_encode arrays with iso-8895 characters
I have a quite complex, even though not really big, array, with many levels of nesting. The array contains values that are encoded in ISO-8895, and also objects, with the same issue. If I just
json_encode($array)
PHP wil silently encode all the values contining ISO-8895 characters as null
.
Looking at the PHP documentation, I managed to write a working solution:
function fixMultibyteSerializedObject($match)
{
return 's:' . mb_strlen($match[2]);
开发者_StackOverflow中文版}
/**
* Useful to json-encode arrays of objects with ISO-8895 encoded values.
* Does not work with iso-encoded keys
* @param var $object array or object to be encoded
* @param int $options json_encode options
*/
function isoJsonEncode($object, $options = null)
{
$str = serialize($object);
$str = mb_convert_encoding($str, 'utf-8');
$str = preg_replace_callback(
'!(?<=^|;)s:(\d+)(?=:"(.*?)";(?:}|a:|s:|b:|d:|i:|o:|N;))!s',
'fixMultibyteSerializedObject',
$str);
$object = unserialize($str);
return json_encode($object, $options);
}
Apart from getting a better library, such as the Zend json encoding component, can you suggest a better solution?
Thank you, Iacopo
What about something like this?
array_walk_recursive($array, function (&$elem) {
if (is_string($elem)) {
$elem = iconv('ISO-8895', 'UTF-8', $elem);
}
});
echo json_encode($array);
精彩评论