2015-06-29 4 views
16

Sto utilizzando Laravel (un framework PHP) per scrivere un servizio per dispositivi mobili e avere i dati restituiti nel formato JSON. Nel risultato dei dati ci sono alcuni campi codificati in UTF-8.'Caratteri non corretti UTF-8, probabilmente erroneamente codificati' in Laravel

la seguente dichiarazione

return JsonResponse::create($data); 

restituisce l'errore sotto

InvalidArgumentException 
HELP 
Malformed UTF-8 characters, possibly incorrectly encoded 

Open: /var/www/html/vendor/symfony/http-foundation/Symfony/Component/HttpFoundation/JsonResponse.php 
     } catch (\Exception $exception) { 
      restore_error_handler(); 

      throw $exception; 
     } 

     if (JSON_ERROR_NONE !== json_last_error()) { 
      throw new \InvalidArgumentException($this->transformJsonError()); 
     } 

Ho cambiato:

return JsonResponse::create($data); 

a

return JsonResponse::create($data, 200, array('Content-Type'=>'application/json; charset=utf-8')); 

ma ancora non funziona.

Come posso risolvere il problema?

+0

Che cos'è '$ data'? Da dove viene, cosa c'è dentro, come fai a sapere che è codificato in UTF-8? – deceze

+0

$ data è dati di matrice dal database. Ho controllato $ data, ha una stringa "兆 琪" => errore quando restituisco json. –

+0

Risolto, è un mio errore. Avere un codice di linea non buono: substr ('兆 琪', ...) Grazie! –

risposta

24

Ho scritto questo metodo, per gestire matrici UTF8 e problemi JSON. Funziona bene con array (semplice e multidimensionale).

/** 
* Encode array from latin1 to utf8 recursively 
* @param $dat 
* @return array|string 
*/ 
    public static function convert_from_latin1_to_utf8_recursively($dat) 
    { 
     if (is_string($dat)) { 
     return utf8_encode($dat); 
     } elseif (is_array($dat)) { 
     $ret = []; 
     foreach ($dat as $i => $d) $ret[ $i ] = self::convert_from_latin1_to_utf8_recursively($d); 

     return $ret; 
     } elseif (is_object($dat)) { 
     foreach ($dat as $i => $d) $dat->$i = self::convert_from_latin1_to_utf8_recursively($d); 

     return $dat; 
     } else { 
     return $dat; 
     } 
    } 
// Sample use 
// Just pass your array or string and the UTF8 encode will be fixed 
$data = convert_from_latin1_to_utf8_recursively($data); 
0

Nel mio caso, questo causa l'errore:

return response->json(["message" => "Model status successfully updated!", "data" => $model], 200); 

ma questo non:

return response->json(["message" => "Model status successfully updated!", "data" => $model->toJson()], 200); 
0

Questo errore si verifica anche se non si attiva il database MySQL o Oracle, ecc ..