PHP 5.6.29 Released

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

Description

string json_last_error_msg ( void )

Parameters

This function has no parameters.

Return Values

Returns the error message on success, "No Error" if no error has occurred, or FALSE on failure.

See Also

add a note add a note

User Contributed Notes 3 notes

up
8
Anonymous
1 year 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
-2
seregynp at gmail dot com
2 years 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
-7
Ess
3 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