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

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大