• PHP Video Tutorials

PHP - json_last_error_msg() Function



The json_last_error_msg() function can return an error string of last json_encode() or json_decode() call.

Syntax

string json_last_error_msg( void )

The json_last_error_msg() function can return an error message on success, "No Error" if no error has occurred, or false on failure. This function doesn't have any parameters.

Example 1

<?php
   $json = '{"name": "Adithya", "age": 20 }';

   $decode = json_decode($json, true);
   $last_error = json_last_error_msg();
   if(strtolower($last_error) != "No Error") {
      echo "ERROR: " . $last_error; die; 
   }
?>  

Output

ERROR: No error

Example 2

<?php
   $json = '{"site":"dev.tutorialspoint.com","topics":{"PHP":"Y","JSON":"Y"]}';
   print("\nInput: ".$json."\n");

   $array = json_decode($json,true);

   if(json_last_error() == JSON_ERROR_NONE) {
      print("\nOutput Array:\n");
      print(" Type: " . gettype($array) . "\n");
      print(" Size: " . count($array) . "\n");
      print(" ['site']: " . $array["site"] . "\n");
      print(" ['topics']['JSON']: " . $array["topics"]["JSON"] . "\n");

      print("\n Output Array Dump:\n");
      var_dump($array);
   } else {
      print("\n json_decode() error: " . json_last_error_msg(). "\n");
   }
?>

Output

Input: {"site":"dev.tutorialspoint.com","topics":{"PHP":"Y","JSON":"Y"]}

json_decode() error: State mismatch (invalid or malformed JSON)
php_function_reference.htm
Advertisements