Using JSON in PHP
1. json_encode()
This function is used to transform array and objects to JSON format. First let's look one array example.
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
the result is
{"a":1,"b":2,"c":3,"d":4,"e":5}
We look one example of object transformation.
$obj->body = 'another post';
$obj->id = 21;
$obj->approved = true;
$obj->favorite_count = 1;
$obj->status = NULL;
echo json_encode($obj);
the result is
{
"body":"another post",
"id":21,
"approved":true,
"favorite_count":1,
"status":null
}
Since JSON can only accept UTF-8 encoded characters, so parameters of json_encode() must be utf-8 encoded, otherwise the result will be empty or null. So we need to take care when we use Chinese's GB2312 encoding or some other languages' ISO-8859-1 encoding.
2. Indexed array and associative array
PHP supports two kinds of arrays, one is indexed array which only stores the value, the other is associative array which stores name/value pairs.
Since JavaScript doesn't support associative array, so json_encode() will transform indexed array into array format, while transform associative array into object format.
For example, we have an indexed array
$arr = Array('one', 'two', 'three');
echo json_encode($arr);
the result will be
["one","two","three"]
If we have an associative array
$arr = Array('1'=>'one', '2'=>'two', '3'=>'three');
echo json_encode($arr);
the result will be
{"1":"one","2":"two","3":"three"}
Note, data format has changed from [] to {}.
If you want to forcibly transform indexed array into object, you can
json_encode( (object)$arr );
or
json_encode ( $arr, JSON_FORCE_OBJECT );
3. Transformation of classHere is a PHP class
class Foo {
const ERROR_CODE = '404';
public $public_ex = 'this is public';
private $private_ex = 'this is private!';
protected $protected_ex = 'this should be protected';
public function getErrorCode() {
return self::ERROR_CODE;
}
}
now we do JSON transformation.
$foo = new Foo;
$foo_json = json_encode($foo);
echo $foo_json;
the result is
{"public_ex":"this is public"}
we can see that only public variables are transformed. All rest will be ignored.
4. json_decode()
To transform JSON data to PHP data structure. For example
$json = '{"foo": 12345}';
$obj = json_decode($json);
print $obj->{'foo'}; // 12345
Usually, json_decode() will return a PHP object instead of array.
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
the result is a PHP object
object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
If we want to forcibly to transform JSON into an array, we need to add one more parameter true to json_decode().
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json,true));
the result is an associative array
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
5. Common mistakes of json_decode()
Following three JSON example have syntax errors. Where is the error?
$bad_json = "{ 'bar': 'baz' }";
$bad_json = '{ bar: "baz" }';
$bad_json = '{ "bar": "baz", }';
the json_decode() will return null for the above three strings.
The first error is, delimiter of JSON can only be double quote, cannot be single quote. The second error is the name of the name/value pair of JSON must be surrounded with double quote. The last error is the last value cannot have trailing comma.
Also JSON can only be used to represent object and array, if we use json_decode() on a string or number, it will return null.
var_dump(json_decode("Hello World")); //null
References
* Ed Finkler, JSON is Everybody's Friend
Original author : 阮一峰 Source : http://www.ruanyifeng.com/blog/2011/01/json_in_php.html
By clicking the "Mark as important" button, this article will be put to your important article list which you can find in "Amin->Article important list". Later when you want reread this article, it's easier for you to find it by checking the "Article important list".
Tags:JSON,PHP,json_decode(0,json_encode() Read(6145) Comment(1)
Previous : this in JavaScript Next : Unix Philosophy
::Related Articles
::Comment Zone
| joelmob (joel.moberg@gmail.com) [Reply] | @ 2012-05-07 08:59:42 |
Here is a snippet on how to get JSON from your SQL server with PHP and MySQLi | |
::Comment
:: Other versions
No other versions available yet.
:: Recent articles
- The new Surface RT may use Qualcomm Snapdragon processor
- Fab CEO: Why we choose Tencent in China?
- Huawei is open to acquire Nokia
- HTML Email Guide
- Use of Erlang in WhatsApp
- Write high quality JavaScript and CSS with SublimeLinter
- Is Facebook developing RSS reader?
- About tmpfs
- Differences among Enter,F5 and Ctrl+F5 in webpage refresh
- China to expand 4G network across the country
- more>>
:: Most read
- TIOBE : C overtakes Java as the No.1 programming language
- Sony is to release PlayStation4 in 2015
- Which programming language should I learn first?
- Disposable Email address
- 5 Free Open Source Chat Applications For Developers
- Never ever touch a programmer
- Hacking Vs. Programming
- TIOBE : Where is that next big programming language?
- Multitasking vs multiprogramming
- Google is developing advanced programming technology to simplify Web application development
- more>>
:: Most commented
- Hacking Vs. Programming
- Which programming language should I learn first?
- Error handling style in C
- 10 controversial programming opinions?
- C vs Java Complete Comparison
- Google+ is sick
- Disposable Email address
- Unix Philosophy
- 20 bit operations programmers should know
- PHP to get access token for Facebook app
- more>>
:: Contribute
Write article:: Find us
