PHP JSON data Processing Instance program Usage _php Tutorial

Source: Internet
Author: User
Tags fread php json
In PHP, the most commonly used JSON data processing is directly using the Json_encode () and the Json_decode () function to deal with, he next I on these two JSON processing functions to the students in detail about JSON in the application of various uses, I hope all the help.

Json_encode (), PHP data->json

Json_encode has only one parameter, and the parameter can be any data type except the resource type. But we typically pass in an array, as in the following example

The code is as follows Copy Code

$arr = Array (
"Name" = "Manson",
"Age" = 23,
"Sex" = 1
);

$json _str = Json_encode ($arr);
Var_dump ($json _str);

The result is a JSON string


{"Name": "Manson", "Age": +, "Sex": 1}

This is usually the conversion of the string output to the front-end processing, often used in Ajax to do data interaction, or some front-end template data output. Json_encode need to pay attention to a problem is the Chinese coding problem, if the PHP page encoding is non-utf-8, before Json_encode, must have the Chinese content of the part to convert to utf-8 encoding, or output to the front end will be garbled. There are many ways to solve this, here's a simple code conversion example

The code is as follows Copy Code
$arr = Array (
"Name" = "Zhang San",
"Age" = 23,
"Sex" = 1
);

$arr [' name '] = Iconv ("GBK", "Utf-8", $arr [' name ']);

$json _str = Json_encode ($arr);

PHP Data

Json_decode has two parameters, the first parameter is the JSON string to be decoded, the incoming must be a canonical JSON format, in fact, Json_decode is json_encode inverse process

The code is as follows Copy Code

$json _str = ' {' name ': ' Manson ', ' age ': $, ' Sex ': 1} ';

$arr = Json_decode ($json _str,true);
Var_dump ($arr);


It should be noted here that the 2nd parameter of the Json_decode is true, meaning that after decoding returns the array format, if passed false or does not pass the 2nd parameter, decodes will return the object format, for example the above code returns the object format is

The code is as follows Copy Code
Object (StdClass) #1 (3) {
["Name"]=>
String (6) "Manson"
["Age"]=>
Int (23)
["Sex"]=>
Int (1)
}

Object format relative to the format of the array, the difficulty of obtaining the corresponding data will increase, especially for multi-level data structure, or the conversion of the form of the number of arrays is good, that is, json_decode the 2nd parameter to remember to pass true.

Processing the submitted JSON data

The Post method (also noted in Get mode) submits a JSON data to PHP, such as:

The code is as follows Copy Code

{"A": 1, "B": 2}

Remove this data in PHP:

The code is as follows Copy Code

$s =$_post[' data '];//or $_get[' data ']

The string is then escaped after it has been removed:

The code is as follows Copy Code

{"A": 1, "B": 2}

If you call directly:

The code is as follows Copy Code

$obj = Json_decode ($s);

Print_r ($obj);
Echo $obj->a;

Is wrong and will report an error.

If $s is defined directly:

The code is as follows Copy Code

$s = ' {' A ': 1, ' B ': 2} ';

There is no problem.

So you need to do some escaping when working with JSON in PHP:

The code is as follows Copy Code

$s =stripslashes ($_post[' data ');

This will allow the JSON decoding to be done.

PHP Get interface Content


Assuming that the interface file page is:/api.php?action=open_getbloglist&only_recommend=1&limit=5, then we can use the following statement to get the contents of this interface file:

The code is as follows Copy Code
$handle = fopen ("/api.php?action=open_getbloglist&only_recommend=1&limit=5", "RB");
$content = "";
while (!feof ($handle)) {
$content. = Fread ($handle, 10000);
}
Fclose ($handle);

In this way, content is stored in the JSON API.

PHP parses the JSON and displays
The original content cannot be called directly, and must be further processed by PHP before it can be called to be displayed in the Web page. In PHP 5.2 and later, use the Json_decode () function to parse the JSON data into a data format that PHP can call. For example:

The code is as follows Copy Code
$content = Json_decode ($content);

After parsing, we can invoke the data in JSON just like the method in PHP that calls array data. This call method needs to be written in the specific JSON data format, see below for a demonstration. About the use of the Json_decode function, specific to the PHP manual, here no longer repeat: http://php.net/manual/en/function.json-decode.php

Real-Combat API


Careful friends will find the Stalker M blog sidebar Most of the bottom of a "friend recommended" module, which recommended some of the Jones blog articles.

Friends of the recommendation is a blog initiative of the Jones blog communication between the way, more effective than traditional links, while the realization of the content of the blog complementary. Since the blog program of the Joan blog was written by himself, he provided the JSON API interface to get the latest and recommended articles.

I use PHP to get this JSON interface, and then output to their own blog sidebar, the following to combat the actual operation.

The first step is to see how the API calls


According to the documentation, I used a parameter like/api.php?action=open_getbloglist&only_recommend=1&limit=5, which means to invoke five of his recommended articles.

The second step is to get the API structure data
Very simple, as mentioned above, the specific code is as follows:

The code is as follows Copy Code
$handle = fopen ("/api.php?action=open_getbloglist&only_recommend=1&limit=5", "RB");
$content = "";
while (!feof ($handle)) {
$content. = Fread ($handle, 10000);
}

Fclose ($handle); Open the data file, and then save everything in the content variable, because you can be sure that the API data will not exceed 10,000 characters, so use 10000 as the second parameter of the Fread function. In this way, the JSON data returned by the API is stored in the content variable.

Step three, parse and output the content
Use the following code to parse the data, and then call the output

The code is as follows Copy Code

$content = Json_decode ($content);
foreach ($content->data as $key) {
Echo '

  • B_url. ' " > '. $key->b_title. '
  • ';
    }

    First of all, the JSON data in the content variables, then become PHP can call the data, and then use the foreach traversal output of the five content, according to the HTML format I need to insert the content.

    http://www.bkjia.com/PHPjc/631542.html www.bkjia.com true http://www.bkjia.com/PHPjc/631542.html techarticle in PHP, the most commonly used JSON data processing is directly using the Json_encode () and the Json_decode () function to deal with, he next I on these two JSON processing functions to the students in detail JSON in the application ...

  • 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.