Home Backend Development PHP Tutorial PHP using json_PHP tutorial

PHP using json_PHP tutorial

Jul 13, 2016 pm 05:49 PM
javascript json php use Can Base object Will of express

JSON Basics
Simply put, JSON converts a set of data represented in a JavaScript object into a string, which can then be easily passed between functions, or from a web client to a server in an asynchronous application terminal program. This string looks a little weird (you'll see a few examples later), but JavaScript interprets it easily, and JSON can represent more complex structures than name/value pairs. For example, arrays and complex objects can be represented rather than just simple lists of keys and values.
Simple JSON example
In its simplest form, a name/value pair can be represented in JSON like this:


This example is very basic and actually takes up more space than the equivalent plain text name/value pair:


However, JSON comes into its own when you string multiple name/value pairs together. First, you can create a record containing multiple name/value pairs, such as:


Syntactically, this isn't a huge advantage over name/value pairs, but in this case JSON is easier to use and more readable. For example, it makes it clear that the above three values ​​are part of the same record; the curly braces make the values ​​somehow related.
Array of values
JSON improves readability and reduces complexity when you need to represent a set of values. For example, suppose you want to represent a list of people's names. In XML, many start and end tags are required; if you use typical name/value pairs (like the ones you saw in previous articles in this series), a proprietary data format must be created , or change the key name to the form person1-firstName.
If using JSON, just group multiple records together with curly braces:


This is not difficult to understand. In this example, there is only one variable called people, and the value is an array of three entries, each entry being a record for a person containing a first name, last name, and email address. The above example demonstrates how to use parentheses to combine records into a single value. Of course, multiple values ​​(each containing multiple records) can be expressed using the same syntax:


The most noteworthy thing here is the ability to represent multiple values, each of which in turn contains multiple values. However, it should also be noted that the actual name/value pairs in the record can differ between different main entries (programmers, authors, and musicians). JSON is fully dynamic, allowing the way data is represented to change in the middle of the JSON structure.
There are no predefined constraints that need to be adhered to when working with JSON-formatted data. Therefore, within the same data structure, the way the data is represented can be changed, and the same thing can even be represented in different ways.
Using JSON in JavaScript
Once you master the JSON format, using it in JavaScript is simple. JSON is a native JavaScript format, which means that processing JSON data in JavaScript does not require any special API or toolkit.
Assign JSON data to variables
For example, you can create a new JavaScript variable and assign a JSON-formatted data string directly to it:


This is very simple; now people contains the data in the JSON format we saw earlier. However, this is not enough as the way to access the data does not seem obvious yet.
Access data
Although it may not seem obvious, the long string above is actually just an array; you can easily access this array by placing it in a JavaScript variable. In fact, just use dot notation to represent array elements. So, to access the last name of the first entry in the programmers list, just use code like this in JavaScript:


Note that array indexing is zero-based. So, this line of code first accesses the data in the people variable; then moves to the entry called programmers, then moves to the first record ([0]); and finally, accesses the value of the lastName key. The result is the string value "McLaughlin".
Here are a few examples using the same variable.


With such a syntax, any JSON formatted data can be processed without using any additional JavaScript toolkit or API.
Modify JSON data
Just as data can be accessed using periods and brackets, data can be easily modified in the same way:


After converting the string to a JavaScript object, you can modify the data in the variable like this.
Convert back to string
Of course, all data modifications are of little value if you can't easily convert the object back to the text format mentioned in this article. This conversion is also simple in JavaScript:


That’s it! You now have a text string that you can use anywhere, for example, as a request string in an Ajax application. www.2cto.com
What's more, any JavaScript object can be converted to JSON text. It is not only possible to handle variables originally assigned with JSON strings. To convert an object named myObject, just execute a command of the same form:


This is the biggest difference between JSON and the other data formats discussed in this series. If you use JSON, you only need to call a simple function to get the formatted data, which is ready to use. For other data formats, conversion between raw and formatted data is required. Even when using an API like the Document Object Model (which provides functions to convert your own data structures to text), you need to learn the API and use the API's objects instead of using native JavaScript objects and syntax.
The bottom line is that if you're dealing with a large number of JavaScript objects, JSON is almost certainly a good choice so that you can easily convert the data into a format that can be sent to the server-side program in the request.
Application of JSON in PHP
In today's Internet, AJAX is no longer an unfamiliar word. Speaking of AJAX, XML that emerged due to RSS may immediately come to mind. XML parsing is probably no longer a problem, especially with PHP5 and the emergence of a large number of XML parsers, such as the most lightweight SimpleXML. However, for AJAX, XML parsing is more inclined to the support of front-end Javascript. I think everyone who has parsed XML will be confused by trees and nodes. It is undeniable that XML is a very good data storage method, but its flexibility makes it difficult to parse. Of course, the difficulty referred to here is relative to the protagonist of this article - JSON.
What is JSON? I won't repeat the concept. In layman's terms, it is a data storage format, just like a PHP serialized string. It is a data description. For example, if we serialize an array and store it, it can be easily deserialized and applied. The same is true for JSON, except that it builds an interactive bridge between client-side Javascript and server-side PHP. We use PHP to generate the JSON string, and then pass this string to the front-end Javascript. Javascirpt can easily convert it into JSON and then apply it. To put it in layman's terms, it really looks like an array.
Closer to home, how to use JSON. PHP5.2 has built-in support for JSON. Of course, if it is lower than this version, there are many PHP version implementations on the market, just use whichever one you want. Now we mainly talk about the JSON built-in support of PHP. Very simple, two functions: json_encode and json_decode (very similar to serialization). One for encoding and one for decoding. Let’s take a look at the use of encoding first:


$arr = array(
'name' => 'Linux',
'nick' => 'php',
'contact' => array(
'email' => 'email',
'website' => 'http://blog.csdn.net/21aspnet,
)
);
$json_string = json_encode($arr);
echo $json_string;
?>
It's very simple to JSON an array. It should be pointed out that under non-UTF-8 encoding, Chinese characters cannot be encoded, and the result will be null. Therefore, if you use gb2312 to write PHP code, you need to use iconv or mb to convert the content containing Chinese to UTF-8 and then json_encode, I have said that it is very similar to serialization, but you still don’t believe it. After encoding, it is necessary to decode. PHP provides the corresponding function json_decode. After json_decode is executed, an object will be obtained. The operation is as follows:

$arr = array(
'name' => 'Linux',
'nick' => 'php',
'contact' => array(
'email' => 'email',
'website' => 'http://blog.csdn.net/21aspnet,
)
);
$json_string = json_encode($arr);
$obj = json_decode($json_string);
print_r($obj);
?>
Is it possible to access the properties within the object? $obj->name, like this, of course, you can also convert it to an array for easy calling:

$json_string = json_encode($arr);
$obj = json_decode($json_string);
$arr = (array) $obj;
print_r($arr);
PHP is not very useful for moving around. In addition to cache generation, it feels like it is better to store the array directly. However, its role comes out when you interact with the front desk. Let's see how I use Javascript to use this. segment characters.
In the above, directly assign this string to a variable, and it becomes a Javascript array (the professional terminology should not be called an array, but due to PHP's habits, I will always call it an array for easier understanding). In this way, you can easily traverse arr or do whatever you want. I haven’t mentioned AJAX yet, right? Yes, think about it, if the responseText returned by the server uses a JSON string instead of XML, wouldn't it be very convenient for the front-end Javascript to process it? This is how dog skin plaster is used.
In fact, as I write this, except for the different data storage formats, there is not much difference between JSON and XML, but there is one point I will mention below. Although it has little to do with XML, it can illustrate the wider application of JSON, that is, cross-domain data calls. Due to security issues, AJAX does not support cross-domain calls. It is very troublesome to call data under different domain names. Although there are solutions (Stone mentioned proxies in his lecture, I don’t understand it but I know it) can be solved). I wrote two files, which are enough to demonstrate cross-domain calls.
Main file index.html



The adjusted file profile.php
$arr = array(
'name' => 'Linux',
'nick' => 'php',
'contact' => array(
'email' => 'email',
'website' => 'http://blog.csdn.net/21aspnet,
)
);
$json_string = json_encode($arr);
echo "getProfile($json_string)";
?>
Obviously, when index.html calls profile.php, a JSON string is generated and passed to getProfile as a parameter, and then the nickname is inserted into the div. In this way, a cross-domain data interaction is completed. Isn't it particularly simple? Since JSON is so simple and easy to use, what are you waiting for? ^_^


Excerpted from Liu Haichuang’s column
zz

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/478336.htmlTechArticleJSON Basics Simply put, JSON can convert a set of data represented in a JavaScript object into a string, and then This string can be easily passed between functions, or async...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1235
24
How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles