JSON can be interpreted as "the object representation of JavaScript", meaning that the concept of JSON is derived from JavaScript, and for Web development patterns, the following figure must be familiar:
As you can see, the client browser and server-side scripts need to exchange data. For small or unformatted data, it is possible to submit the past directly using a string method with simple post and get, but some large data, preferably with a formatted method of exchange, such as JSON and XML. what is JSON.
JSON a data interchange format used to transmit excess data over the Internet. While it is important to exchange data XML over the Internet, JSON is much simpler and applies to lightweight data.
Although JSON was originally invented by JavaScript and used to access remote data, it is now widely available in a variety of languages, because JSON is a platform-independent data format. data types and instances of JSON data
JSON supports a wide variety of data types, including numbers, strings, Boolean values, array data, and even object data (a collection in which each element is a key: A value pair form, separated by commas, and wrapped in braces).
Let's look at a simple example of a JSON data that represents the details of an employee:
{"id": "1″," name ":" Mike "," Country ":" USA "," Office ": [" Microsoft "," Oracle "]} ways to create and parse JSON data using PHP
PHP provides a JSON extension from 5.2.0 to process JSON data, and PHP has two functions Json_encode () and json_decode very handy for converting and parsing JSON data.
First, let's look at a section of PHP code that uses arrays to create all kinds of JSON:
$json _data = array (' ID ' =>1, ' name ' => ' Mike ', ' Country ' => ' USA ', Office =>array ("Microsoft", "Oracle");
Echo Json_encode ($json _data);
The code produces the JSON data directly. Now let's use PHP to decode the above JSON:
$json _string= ' {"id": 1, "name": "Mike", "Country": "USA", "Office": ["Microsoft", "Oracle"]} ';
$obj =json_decode ($json _string);
Now that the variable $obj contains JSON data that is parsed using PHP, you can use the following methods to output and access:
Echo $obj->name; Displays Mike
echo $obj->office[0];//displays microsoft
You guessed right. $obj->office is an array that you can iterate through using the PHP foreach method:
foreach ($obj->office as $val)
echo $val;