Comment résoudre une erreur JSON UTF8 dans php JSON decode?

j'essaie ce code

$json = file_get_contents("http://www.google.com/alerts/preview?q=test&t=7&f=1&l=0&e");
print_r(json_decode(utf8_encode($json), true));

        //////////////

// Define the errors.
$constants = get_defined_constants(true);
$json_errors = array();
foreach ($constants["json"] as $name => $value) {
    if (!strncmp($name, "JSON_ERROR_", 11)) {
        $json_errors[$value] = $name;
    }
}

// Show the errors for different depths.
foreach (range(4, 3, -1) as $depth) {
    var_dump(json_decode($json, true, $depth));
    echo 'Last error: ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL;
}

j'ai essayé beaucoup de fonctions, html_enties_decode, utf8_encode et decode, décodant les codes hexadécimaux, mais j'obtiens toujours l'erreur"JSON_ERROR_UTF8".

comment résoudre cela?

41
demandé sur BeetleJuice 2012-04-18 00:55:29

3 réponses

Il y a une bonne fonction pour désinfecter vos tableaux.

je vous suggère d'utiliser un wrapper json_encode comme ceci:

function safe_json_encode($value, $options = 0, $depth = 512){
    $encoded = json_encode($value, $options, $depth);
    switch (json_last_error()) {
        case JSON_ERROR_NONE:
            return $encoded;
        case JSON_ERROR_DEPTH:
            return 'Maximum stack depth exceeded'; // or trigger_error() or throw new Exception()
        case JSON_ERROR_STATE_MISMATCH:
            return 'Underflow or the modes mismatch'; // or trigger_error() or throw new Exception()
        case JSON_ERROR_CTRL_CHAR:
            return 'Unexpected control character found';
        case JSON_ERROR_SYNTAX:
            return 'Syntax error, malformed JSON'; // or trigger_error() or throw new Exception()
        case JSON_ERROR_UTF8:
            $clean = utf8ize($value);
            return safe_json_encode($clean, $options, $depth);
        default:
            return 'Unknown error'; // or trigger_error() or throw new Exception()

    }
}

function utf8ize($mixed) {
    if (is_array($mixed)) {
        foreach ($mixed as $key => $value) {
            $mixed[$key] = utf8ize($value);
        }
    } else if (is_string ($mixed)) {
        return utf8_encode($mixed);
    }
    return $mixed;
}

dans mon application utf8_encode() fonctionne mieux que iconv ()

58
répondu Konstantin 2017-12-09 19:30:57

vous avez besoin d'une ligne de code simple:

$input = iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($input));
$json = json_decode($input);

crédit: Sang Le, ma coéquipière m'a donné ce code. Ouais!

48
répondu Andy Truong 2013-06-19 03:31:15

la fonction iconv est sans valeur à moins que vous puissiez garantir la validité de la saisie. Utilisez plutôt mb_convert_encoding.

mb_convert_encoding($value, "UTF-8", "auto");

vous pouvez obtenir plus explicite que" auto", et même spécifier une liste séparée par des virgules des encodages d'entrée attendus.

plus important encore, les caractères invalides seront manipulés sans que la chaîne entière soit écartée (contrairement à iconv).

9
répondu Rich Remer 2014-06-25 17:22:18