json_last_error_msg

(PHP 5 >= 5.5.0, PHP 7)

json_last_error_msgReturns the error string of the last json_encode() or json_decode() call

Açıklama

string json_last_error_msg ( void )

Değiştirgeler

Bu işlevin değiştirgesi yoktur.

Dönen Değerler

Returns the error message on success, "No Error" if no error has occurred, başarısızlık durumunda FALSE döner.

Ayrıca Bakınız

add a note add a note

User Contributed Notes 3 notes

up
8
Anonymous
8 months ago
Here's an updated version of the function:

<?php
   
if (!function_exists('json_last_error_msg')) {
        function
json_last_error_msg() {
            static
$ERRORS = array(
               
JSON_ERROR_NONE => 'No error',
               
JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
               
JSON_ERROR_STATE_MISMATCH => 'State mismatch (invalid or malformed JSON)',
               
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
               
JSON_ERROR_SYNTAX => 'Syntax error',
               
JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded'
           
);

           
$error = json_last_error();
            return isset(
$ERRORS[$error]) ? $ERRORS[$error] : 'Unknown error';
        }
    }
?>
up
0
seregynp at gmail dot com
1 year ago
Watch out !

In case no error occurred, 'No error' still returned !

So when upgrading to php 5.5, unexpected behavior can be:

<?php
if ($error = json_last_error_msg()) {
   throw new \
LogicException(sprintf("Failed to parse json string '%s', error: '%s'", $this->data, $error));
}

// in php 5.5 exception will be thrown, while as in older version not
?>
up
-1
Ess
2 years ago
If function not exists

<?php
if (!function_exists('json_last_error_msg'))
    function
json_last_error_msg()
    {
        switch (
json_last_error()) {
            default:
                return;
            case
JSON_ERROR_DEPTH:
               
$error = 'Maximum stack depth exceeded';
            break;
            case
JSON_ERROR_STATE_MISMATCH:
               
$error = 'Underflow or the modes mismatch';
            break;
            case
JSON_ERROR_CTRL_CHAR:
               
$error = 'Unexpected control character found';
            break;
            case
JSON_ERROR_SYNTAX:
               
$error = 'Syntax error, malformed JSON';
            break;
            case
JSON_ERROR_UTF8:
               
$error = 'Malformed UTF-8 characters, possibly incorrectly encoded';
            break;
        }
        throw new
Exception($error);
    }
?>
To Top