Php reads data and converts it to json output.

Source: Internet
Author: User
Many websites now use the asynchronous loading technology. most of the loaded data formats are json (for example, {& quot; order & quot;: & quot; 205 & quot;, & quot; 205 & quot;: & quot; \ u81ea \ u9009 \ u80a1 & quot;}). The following describes several methods for php to convert data to json output after reading data. First, the simplest

Many websites now use the asynchronous loading technology. most of the loaded data formats are json (for example, {"order": "205", "205 ": "\ u81ea \ u9009 \ u80a1"}). The following describes several methods for converting php Data to json output after reading data.

The first simplest and most commonly used method is to spell strings. I will not describe it here.

The second is to use the json_encode function.

Run the following code:


[Php]
Var_dump (json_decode ('{"order": "205", "205": "\ u81ea "}'));

Var_dump (json_decode ('{"order": "205", "205": "\ u81ea "}'));
The result is:

Object (stdClass) #1 (2) {["order"] => string (3) "205" ["205"] => string (3) "self "}


Therefore, a stdClass object needs to be defined before conversion. after assigning values to the object, execute the json_encode function to get the expected result.

Later, we found that defining an array can also be implemented, as long as the final array format is: array (order => 205, "205" => "\ u81ea, in this way, you cannot add new elements to the array in the array_push mode. Instead, you must assign the value $ arr ["order"] = "205" through the index ";

Advantages and disadvantages

The first method is faster than the second method (I have done a demo test), but the disadvantage is that there are many quotation marks and so on when spelling strings, so it is easy to make mistakes if you are not careful.

The second kind is more in line with the object-oriented programming habits and will encode Chinese unicode. The disadvantage is that the process of packaging data and parsing data is slower, but it is completely acceptable.

 

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.