How to get json_encode() to work with ISO-8859-1 (åäö)

前端 未结 8 892
礼貌的吻别
礼貌的吻别 2021-01-11 15:58

json_encode() wont work for me when I\'m using åäö. Why? And how can I get it to work?

The php:

echo json_encode($arr);


        
相关标签:
8条回答
  • 2021-01-11 16:41

    As Greg mentioned, I had to encode åäö to UTF-8. But I did't use iconv or mbstring. When I utf8_encode() all values before putting the values to the array the problem was solved.

    0 讨论(0)
  • 2021-01-11 16:45

    JSON defines strings as Unicode!

    JSON Definition

    You have to encode you ISO to UTF-8

    0 讨论(0)
  • 2021-01-11 16:50

    The $data (in my case) is an array with text values as ISO-8859-1. The trick below prepares $data to be used with json_encode.

    function toUtf8(&$v, $k) {
        $v = utf8_encode($v);
    }
    array_walk_recursive($data, 'toUtf8');
    
    0 讨论(0)
  • 2021-01-11 16:51

    As of PHP 5.4.0:

    Convert your strings in your array to into utf-8 using utf8_encode($str) function.

    Then json_encode with JSON_UNESCAPED_UNICODE option:

    $arr = json_encode($array, JSON_UNESCAPED_UNICODE);

    0 讨论(0)
  • 2021-01-11 16:53

    Using the standard method when reading from MySQL:

    $resultArray = array();
    while($obj = MySQL_fetch_object($res)) {
     $resultArray[] = $obj;
    }
    $result = json_encode($resultArray);
    

    The encoding can be done using the following:

    $resultArray = array();
    while($obj = MySQL_fetch_object($res)) {
     foreach($obj as $key => $value) {
      if (!is_null($value)) {
       $obj->$key = utf8_encode($value);
      }
     }
     $resultArray[] = $obj;
    }
    $result = json_encode($resultArray);
    

    The if is_null has to be included so that null fields (e.g., DateTime fields) remain null in the output.

    0 讨论(0)
  • 2021-01-11 16:58

    It says in the json_encode() documentation:

    This function only works with UTF-8 encoded data.

    You should convert it to utf-8 with iconv or mbstring first.

    0 讨论(0)
提交回复
热议问题