Follow Sinsing to interpret the use of JSON in PHP

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.