當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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 - json_last_error_msg() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。