Since JSON is so important, PHP has added support for JSON since 5.2, mainly including two functions: Json_encode and Json_decode. As we all know, JSON is a kind of data storage format, my it wrote JSON, in my JavaScript tutorial, do not understand the reader can go to search.
For example, we create a new Xin.json file that stores data as follows:
[{"Name": "Sinsing", "Age": 23},{"name": "Xiao Qian", "Age": 20}]
We can write a api.php file and parse the JSON file as follows:
<?php$content = file_get_contents ("Xin.json"), $obj = Json_decode ($content);p rint_r ($obj);
We will find the output as follows:
Array ([0] = StdClass object ([name] = Sinsing [age] = +) [1] = = StdClass object ([name] = [age] =&G T 20))
Well understood, and JavaScript very similar, here Stdclass is the basic class, do not understand the child shoes can go to search, here according to our format to output this JSON data, actually we use them and we use in JavaScript is similar, Then we'll take a separate output style:
<?php$content = file_get_contents ("Xin.json"); $obj = Json_decode ($content); for ($i = 0; $i <count ($obj); $i + +) { echo "Name is:". $obj [$i]->name. "Age is:". $obj [$i]->age. <br/> ";}
Then the output is as follows:
The name is: Sinsing age is: 23 name is: Xiao Qian age is: 20
And the Json_decode function can accept the second parameter, if true, then our JSON data will be converted to an array instead of an object, in fact, objects and arrays are very similar in many cases, and in PHP, the object will not invoke the method.
Since our team Json_decode to figure out, then Json_encode rely on the reader to move hands, very simple ....
Follow Sinsing to interpret the use of JSON in PHP