Asked  7 Months ago    Answers:  5   Viewed   50 times

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).

However, when I try to encode this as json using the php built in json_encode it produces a null json value (OS X server: php 5.3.4, json 1.2.1 enabled).

In a Linux server, the description is cut off after the first accent character.

I tried all the json_encode options with no success. Any suggestions?

Thank you.

 Answers

33

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);

});
Wednesday, March 31, 2021
 
Skipper
answered 7 Months ago
86

Using something like this before Your query to set charset of client and results:

  mysql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'", $conn);
Wednesday, March 31, 2021
 
msg
answered 7 Months ago
msg
31

Change your mysql database/ table / column encoding to UTF-8 (and also set the collation to a compatible value).

ALTER TABLE mytable CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
ALTER TABLE mytable 
MODIFY country CHAR(50) 
CHARACTER SET utf8 COLLATE utf8_general_ci;

Also specify the char set at the PHP side when connecting.

mysql_set_charset('utf8',$conn); 

Take a look at this article for further info and a script to batch change every table / column in a database.

Saturday, May 29, 2021
 
Gilko
answered 5 Months ago
48

and another way:

$input = array(
    'item1'  => 'object1',
    'item2'  => 'object2',
    'item-n' => 'object-n'
);

$output = implode(', ', array_map(
    function ($v, $k) {
        if(is_array($v)){
            return $k.'[]='.implode('&'.$k.'[]=', $v);
        }else{
            return $k.'='.$v;
        }
    }, 
    $input, 
    array_keys($input)
));

or:

$output = implode(', ', array_map(
    function ($v, $k) { return sprintf("%s='%s'", $k, $v); },
    $input,
    array_keys($input)
));
Friday, July 9, 2021
 
Isky
answered 4 Months ago
55

Just use indexOf()

var genre = req.query.genre;
var movies = data.movies;
var filtered = movies.filter(function(x){
    return x.genre.indexOf(genre) > -1;
});
Wednesday, August 25, 2021
 
ALH
answered 2 Months ago
ALH
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :