PHP - json_last_error_msg() 函式



json_last_error_msg() 函式可以返回上次 json_encode() 或 json_decode() 呼叫的錯誤字串。

語法

string json_last_error_msg( void )

json_last_error_msg() 函式在成功時返回錯誤訊息,如果沒有發生錯誤則返回 "No Error",失敗則返回 false。此函式沒有任何引數。

示例 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; 
   }
?>  

輸出

ERROR: No error

示例 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");
   }
?>

輸出

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

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