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

Learn More

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

Forked from Hello World.

95 Runs 1937 Views 193 Copies
Saved

Saved

gtsolutions 373

gtsolutions
published 4 years ago

<?php

/**
 * JSON
 * error management on json_encoding using json_last_error()
 */

echo '<center>';

//code with good  encoding string
echo '<br />
    <div style="background-color:green;color:#000;padding:10px;width:650px;font-size:16px;font-weight:bold">
    <u>json_last_error() usage on json encoding:</u>';
$string = "goose";
echo '<br /><br />Encoding: ' . $string;
json_encode($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>';

//code with bad encoding string
echo '<br />
    <div style="background-color:red;color:#000;padding:10px;width:650px;font-size:16px;font-weight:bold">
    <u>json_last_error() usage on json encoding:</u>';
$string = "goose\xB1\x31";
echo '<br /><br />Encoding: ' . $string;
json_encode($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).