2012-04-17 11 views
39

Sto provando questo codiceCome risolvere l'errore JSON_ERROR_UTF8 in php json_decode?

$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; 
} 

Ho provato un sacco di funzioni, html_entities_decode, utf8_encode e decodifica, decodifica i codici esadecimali, ma ottengo sempre l'errore "JSON_ERROR_UTF8".

Come posso risolvere questo?

+1

io non sono sicuro perché l'errore è venuta fuori come un errore UTF8 . Il JSON restituito da quell'URL non è valido poiché utilizza le virgolette singole dove dovrebbe essere usato il doppio. Non passa JSON LINT (http://jsonlint.com/). Detto questo, presumo che '$ x' sulla riga 2 del tuo codice dovrebbe essere' $ json'? – JAAulde

+0

Sì, stavo pulendo il codice e ho dimenticato di cambiare $ x, hai provato a renderlo valido e poi a decodificarlo? Non saprei come renderlo valido. –

+0

Ho provato a sostituire tutte le virgolette singole con il doppio, ma poi ad incontrare altri problemi di convalida. Ancora dando un'occhiata. – JAAulde

risposta

44

È necessario semplice riga di codice:

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

credito: Sang Le, il mio teamate mi ha dato questo codice. Si!

+1

Non funziona per me 'PHP Avviso: iconv(): Rilevato un carattere non valido nella stringa di input in /tmp/parse_json.php sulla riga 4'. E restituisce false – mente

+4

Grazie, amico! Mi hai salvato la giornata! – null

+0

questo è fantastico, grazie – caro

6

La funzione iconv è piuttosto inutile a meno che non si possa garantire che l'input sia valido. Usa invece mb_convert_encoding.

È possibile ottenere più esplicito di "auto" e persino specificare un elenco separato da virgole delle codifiche di ingresso previste.

Principalmente, i caratteri non validi verranno gestiti senza che l'intera stringa venga scartata (diversamente da iconv).

48

There is a good function per disinfettare i vostri array.

vi suggerisco di utilizzare un wrapper json_encode come questo:

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

Nella mia applicazione utf8_encode() funziona meglio di iconv()

+0

Funziona per me. Grazie! – perelin

+0

finalmente, qualcosa che in realtà ha funzionato per me! grazie!! – userX

+0

Grazie. Ha funzionato per me –

Problemi correlati