Php json data processing instance program usage

Source: Internet
Author: User
Tags php json
In php, the most common JSON data processing function is to directly use the json_encode () and json_decode () functions for processing. The two json processing functions are described in detail in the application of json.

In php, the most commonly used JSON data processing is to directly use the json_encode () and json_decode () functions for processing. These two json processing functions are used to introduce the usage of json in applications.

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. the code is as follows:

  1. $ Arr = array (
  2. "Name" => "manson ",
  3. "Age" => 23,
  4. "Sex" => 1
  5. );
  6. $ Json_str = json_encode ($ arr );
  7. Var_dump ($ json_str );

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:

  1. $ Arr = array (
  2. "Name" => "James ",
  3. "Age" => 23,
  4. "Sex" => 1
  5. );
  6. $ Arr ['name'] = iconv ("gbk", "UTF-8", $ arr ['name']);
  7. $ 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:

  1. $ Json_str = '{"name": "manson", "age": 23, "sex": 1 }';
  2. $ Arr = json_decode ($ json_str, true );
  3. 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 returned object format is as follows:

  1. Object (stdClass) #1 (3 ){
  2. ["Name"] =>
  3. String (6) "manson"
  4. ["Age"] =>
  5. Int (23)
  6. ["Sex"] =>
  7. Int (1)
  8. }

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: {"a": 1, "B": 2}

Retrieve the data in PHP: $ s =$ _ POST ['data']; // or $ _ GET ['data']

Then the string is escaped: {"a": 1, "B": 2}

If you call:

  1. $ Obj = json_decode ($ s );
  2. Print_r ($ obj );
  3. Echo $ obj->;

Yes. an error is reported. if $ s is defined as $ s = '{"a": 1, "B": 2}', no problem occurs, therefore, when processing JSON in PHP, you need to perform escape processing: $ s = stripslashes ($ _ POST ['data']); then you can perform json decoding.

PHP obtains the 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:

  1. $ Handle = fopen ("/api. php? Action = open_getBlogList & only_recommend = 1 & limit = 5 "," rb ");
  2. $ Content = "";
  3. While (! Feof ($ handle )){
  4. $ Content. = fread ($ handle, 10000 );
  5. }
  6. Fclose ($ handle );

In this way, the content is saved as the JSON api content. PHP parses the JSON and displays the content. The original content cannot be directly called and must be further processed by PHP before being 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: $ content = json_decode ($ content );

After parsing, we can call the data in JSON in the same way as the method for calling array data in PHP. this call method needs to be written in the specific JSON data format. for 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:

  1. $ Handle = fopen ("/api. php? Action = open_getBlogList & only_recommend = 1 & limit = 5 "," rb ");
  2. $ Content = "";
  3. While (! Feof ($ handle )){
  4. $ Content. = fread ($ handle, 10000 );
  5. }

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

  1. $ Content = json_decode ($ content );
  2. Foreach ($ content-> data as $ key ){
  3. Echo'
  4. . $ Key-> B _url. '">'. $ key-> B _title .'
  5. ';
  6. }
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.

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.