Php json data processing instance usage _ PHP Tutorial

Source: Internet
Author: User
Tags php json
Php json data processing instance program usage. In php, JSON data processing is most commonly used by using the json_encode () and json_decode () functions for processing, next, I will introduce the two json processing functions to you in detail. in the application of json, the most common JSON data processing in php is to directly use the json_encode () and json_decode () functions for processing, he will introduce the usage of json in the application to these two json processing functions in detail, and hope to help you all.

Json_encode (), PHP Data-> JSON

Json_encode has only one parameter. in addition to the resource type, the parameter can be of any data type. But we generally input an array, as shown in the following example.

The code is as follows:

$ 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": 23, "sex": 1}

In this case, the converted string is usually output to the front-end for processing. it is often used for ajax for data interaction or data output from some front-end templates. Json_encode is a problem of Chinese Encoding. if the PHP page encoding is not UTF-8, you must convert the part with Chinese content to UTF-8 before json_encode, otherwise, garbled characters are generated at the front end. There are many solutions on the internet. here is a simple code conversion example.

The code is as follows:
$ Arr = array (
"Name" => "James ",
"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 input must be in the standard json format. In fact, json_decode is the inverse process of json_encode.

The code is as follows:

$ Json_str = '{"name": "manson", "age": 23, "sex": 1 }';

$ Arr = json_decode ($ json_str, true );
Var_dump ($ arr );


It should be noted that the 2nd json_decode parameters are set to true, meaning that the array format is returned after decoding. if the parameter is set to false or 2nd parameters are not set, after decoding, the system will return the object format. for example, the format of the object returned by the above code is

The code is as follows:
Object (stdClass) #1 (3 ){
["Name"] =>
String (6) "manson"
["Age"] =>
Int (23)
["Sex"] =>
Int (1)
}

Compared with the array format, the object format is more difficult to obtain the corresponding data. especially for multi-level data structures, it is better to convert the data into arrays, that is, remember to pass true to the json_decode 2nd parameter.

Process submitted JSON data

The POST method (pay attention to the GET method) submits a JSON data to PHP, for example:

The code is as follows:

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

Retrieve the data in PHP:

The code is as follows:

$ S = $ _ POST ['data']; // or $ _ GET ['data']

After this string is extracted, it is escaped:

The code is as follows:

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

If you call:

The code is as follows:

$ Obj = json_decode ($ s );

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

Yes. an error is reported.

If $ s is defined directly:

The code is as follows:

$ S = '{"a": 1, "B": 2 }';

No problem.

Therefore, when processing JSON in PHP, you need to perform the following escape operations:

The code is as follows:

$ S = stripslashes ($ _ POST ['data']);

Then perform json decoding.

PHP get interface content


Assume that the interface file page is/api. php? Action = open_getBlogList & only_recommend = 1 & limit = 5, then we can use the following statement to obtain the content of this interface file:

The code is as follows:
$ 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 stores the JSON api content.

PHP parses JSON and displays
The original content cannot be called directly. it must be further processed by PHP before it can be called and displayed on the webpage. In PHP 5.2 and later versions, use the json_decode () function to parse JSON data and convert it to a data format that can be called by PHP. For example:

The code is as follows:
$ Content = json_decode ($ content );

After parsing, we can call JSON data in the same way as calling array data in PHP. This call method needs to be written according to the specific JSON data format. for the demonstration, see the following. About the use of json_decode function, see The PHP Manual, here will not go into detail: http://php.net/manual/en/function.json-decode.php

Practical api


Careful friends will find that a "friend suggestion" module is added at the bottom of the sidebar of the practitioner m blog, which recommends some articles on the Qiongtai blog.

Youwen recommendation is a type of communication between blogs proposed by the Qiongtai blog. it is more effective than traditional friendship links and complements the blog content. Because the blog program of the Qiongtai blog was prepared by himself, he provided the JSON api to obtain the latest recommendable articles.

I use PHP to obtain this JSON interface and output it to the sidebar of my blog. I will perform the following operations in practice.

Step 1: view the api call method


According to the document, I used/api. php? Action = open_getBlogList & only_recommend = 1 & limit = 5, which means to call five articles he recommends.

Step 2: obtain api structure data
The code is as follows:

The code is as follows:
$ Handle = fopen ("/api. php? Action = open_getBlogList & only_recommend = 1 & limit = 5 "," rb ");
$ Content = "";
While (! Feof ($ handle )){
$ Content. = fread ($ handle, 10000 );
}

Fclose ($ handle); first open the data file and save all the content to the content variable, because it is certain that the api data will not exceed 10000 characters, so 10000 is used as the second parameter of the fread function. In this way, JSON data returned by the api is saved in the content variable.

Step 3: Parse and output the content
Use the following code to parse the data and then call the output

The code is as follows:

$ Content = json_decode ($ content );
Foreach ($ content-> data as $ key ){
Echo'

  • B _url. '">'. $ key-> B _title .'
  • ';
    }

    First, process the JSON data in the content variable, and then convert the data that can be called by PHP. Then, use foreach to traverse and output the five contents. insert the content in the HTML format as needed.

    Parse () and json_decode () functions are processed. I will introduce these two json processing functions to you in detail in the application of json...

    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.