How to json_encode array with french accents?

后端 未结 7 2291
离开以前
离开以前 2020-12-05 13:58

I have an array item with a French accent ([WIPDescription] => Recette Soupe à lOignon Sans Boeuf US). The data is being properly pulled from the database (mysql).

相关标签:
7条回答
  • 2020-12-05 14:02

    I found this to be the easiest way to deal with it

    echo json_encode($array, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    

    JSON_PRETTY_PRINT - makes is readable
    JSON_UNESCAPED_UNICODE - encodes characters correctly
    JSON_UNESCAPED_SLASHES - gets rid of escape slash '\'
    also notice that these option are separated by a pipe '|'

    0 讨论(0)
  • 2020-12-05 14:14
    $json = utf8_encode($string);
    
    $json = json_decode($json);
    
    0 讨论(0)
  • 2020-12-05 14:18

    json_encode only wants utf-8. Depending on your character set, you can use iconv or utf8_encode before calling json_encode on your variable. Probably with array_walk_recursive.

    As requested, an unfinished way to alter an array, with the assumptions that (1) it doesn't contain objects, and (2) the array keys are in ascii / lower bounds, so can be left as is:

    $current_charset = 'ISO-8859-15';//or what it is now
    array_walk_recursive($array,function(&$value) use ($current_charset){
         $value = iconv('UTF-8//TRANSLIT',$current_charset,$value);
    
    });
    
    0 讨论(0)
  • 2020-12-05 14:18

    Per the PHP docs

    This function only works with UTF-8 encoded data.

    0 讨论(0)
  • 2020-12-05 14:26
    <? 
    
    $sql=mysql_query("SELECT * FROM TABLE...");
    
    while($row=mysql_fetch_array($sql))
    {
        $output[]=array_map("utf8_encode", $row);
    }
    print(json_encode($output));
    mysql_close();
    
    ?>
    
    0 讨论(0)
  • 2020-12-05 14:27

    Another solution would be to use htmlentities or utf8_encode before using json_encode to pass the encoded char

    like this:

       $array = array('myvalue' => utf8_encode('ééàà'));
       return json_encode($array);
    

    Or using htmlentities :

       $array = array('myvalue' => htmlentities('ééàà'));
       return json_encode($array);
    
    0 讨论(0)
提交回复
热议问题