Manuel PHP

json_last_error

(PHP 5 >= 5.3.0)

json_last_errorReturns the last error occured

Description

int json_last_error ( void )

Returns the last error (if any) occured by last JSON parsing.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Returns an integer, the value can be one of the following constants:

JSON error codes
Constant Meaning
JSON_ERROR_NONE No error has occured
JSON_ERROR_DEPTH The maximum stack depth has been exceeded
JSON_ERROR_CTRL_CHAR Control character error, possibly incorrectly encoded
JSON_ERROR_SYNTAX Syntax error

Exemples

Exemple #1 json_last_error() example

  1. <?php
  2. // A valid json string
  3. $json[] = '{"Organization": "PHP Documentation Team"}';  
  4.  
  5. // An invalid json string which will cause an syntax
  6. // error, in this case we used ' instead of " for quotation
  7. $json[] = "{'Organization': 'PHP Documentation Team'}";  
  8.  
  9.  
  10. foreach($json as $string)  
  11. { 
  12.    echo 'Decoding: ' . $string; 
  13.    json_decode($string); 
  14.  
  15.    switch(json_last_error()) 
  16.    { 
  17.       case JSON_ERROR_DEPTH: 
  18.          echo ' - Maximum stack depth exceeded'; 
  19.       break; 
  20.       case JSON_ERROR_CTRL_CHAR: 
  21.          echo ' - Unxpected control character found'; 
  22.       break; 
  23.       case JSON_ERROR_SYNTAX: 
  24.          echo ' - Syntax error, malformed JSON'; 
  25.       break; 
  26.       case JSON_ERROR_NONE: 
  27.          echo ' - No errors'; 
  28.       break; 
  29.    } 
  30.  
  31.    echo PHP_EOL;  
  32. }  
  33. ?> 

L'exemple ci-dessus va afficher :

Decoding: {"Organization": "PHP Documentation Team"} - No errors Decoding: {'Organization': 'PHP Documentation Team'} - Syntax error, malformed JSON

Voir aussi


Remonter Remonter
L'éditeur javascript - CSS - Gentoo - Tutoriaux PHP - Tutoriels PHP - Bretagne - php - Moto - Kit graphique