duanchuaiwan0063 2011-07-26 12:33
浏览 80
已采纳

json_encode数组,带有iso-8895字符

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]);
}
/**
 * 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

  • 写回答

1条回答 默认 最新

  • duanposhi3641 2011-07-26 13:44
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效