JSON with Php

The common functions of the JSON extension in PHP by default are as follows,

 

json_encode() – Encodes the value into JSON format

Eg:

$arr = array(‘a’ => 1, ‘b’ => 2, ‘c’ => 3, ‘d’ => 4, ‘e’ => 5);

echo json_encode($arr);

 

json_decode() – Decodes tha value from the JSON format

Eg:

$json = ‘{“foo-bar”: 12345}’;

$obj = json_decode($json);

print $obj->{‘foo-bar’};

 

json_last_error() – Returns the last error occurred

Eg:

    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;

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s