Speed up development with full-stack environments for every branch.

Learn More

JSON module example - How to treat JSON decode errors with json_last_error() function

Forked from Hello World.

73 Runs 1032 Views 205 Copies
Saved

Saved

gtsolutions 373

gtsolutions
published 4 years ago

<?php

/**
 * JSON
 * error management on json_decoding using json_last_error() function
 */
// A valid json string
$json[] = '{"Foundation": "Help people to find money"}';

// An invalid json string which will cause an syntax 
// error, in this case we used ' instead of " for quotation
$json[] = "{'Foundation': 'Help people to find money'}";

echo '<center>';
echo '<br />
    <div style="background-color:yellow;color:#000;padding:10px;width:650px;font-size:16px;font-weight:bold">
    <u>json_last_error() usage:</u>';
foreach ($json as $string) {
    echo '<br /><br />Decoding: ' . $string;
    json_decode($string);

    switch (json_last_error()) {
        case JSON_ERROR_NONE:
            echo ' - No errors';
            break;
        case JSON_ERROR_DEPTH:
            echo ' - Maximum stack depth exceeded';
            break;
        case JSON_ERROR_STATE_MISMATCH:
            echo ' - Underflow or the modes mismatch';
            break;
        case JSON_ERROR_CTRL_CHAR:
            echo ' - Unexpected control character found';
            break;
        case JSON_ERROR_SYNTAX:
            echo ' - Syntax error, malformed JSON';
            break;
        case JSON_ERROR_UTF8:
            echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
            break;
        default:
            echo ' - Unknown error';
            break;
    }

    echo PHP_EOL;
}
echo'</div>';
echo '</center>';
?>
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).