A guide to JSON parsing and generation in PHP
With the continuous development and application of Internet technology, front-end and back-end data interaction has become a necessary part of Web development. As a lightweight data exchange format, JSON has become one of the most popular choices. As an important language in the field of web development, PHP also provides a complete JSON processing function library, so developers can easily parse and generate JSON data. This article will introduce how to parse and generate JSON in PHP.
1. Basic concepts of JSON
JSON (JavaScript Object Notation) is a lightweight data exchange format that describes the data structure in a concise textual manner. JSON uses key-value pairs to represent data and supports basic data types, arrays, objects and other data structures. Its syntax is very similar to JavaScript object literals because JSON is derived from JavaScript object literals.
The following is a simple JSON example:
{ "name": "Jack", "age": 22, "address": { "province": "Guangdong", "city": "Shenzhen" }, "hobby": ["reading", "music"] }
The above example contains an object that contains four key-value pairs. Among them, name
and age
are basic data types, address
is an object, and hobby
is an array. As you can see, the format of JSON data is very concise and clear.
2. Parse JSON data
PHP provides the json_decode()
function to parse JSON data. The parameter of this function is a string in JSON format, and the return value is an object or array. If parsing fails, NULL
is returned.
The following is the basic usage of the json_decode()
function:
$jsonStr = '{"name":"Jack","age":22}'; $jsonObj = json_decode($jsonStr); echo $jsonObj->name; // 输出 Jack echo $jsonObj->age; // 输出 22
In the above example, a JSON format string is first defined$jsonStr
, which represents an object containing key-value pairs of name
and age
. Next, use the json_decode()
function to parse $jsonStr
into an object $jsonObj
. Finally, the values of name
and age
are accessed through the $jsonObj
object and output.
When the JSON data contains arrays or deeper nested structures, the json_decode()
function can automatically parse it into a multi-dimensional array. The following is a JSON example containing arrays and objects:
$jsonStr = '{ "name": "Jack", "friends": [ { "name": "Tom", "age": 22 }, { "name": "Jerry", "age": 23 } ] }'; $jsonArr = json_decode($jsonStr, true); echo $jsonArr['friends'][0]['name']; // 输出 Tom
In the above example, since the second parameter is set to true
, json_decode()
returns Is an associative array rather than an object. The data in $jsonArr
can be accessed through multi-dimensional array indexing.
3. Generate JSON data
PHP also provides the json_encode()
function to convert an object or array into a JSON string, which can be used directly Front-end and back-end data interaction.
The following is the basic usage of the json_encode()
function:
$data = [ 'name' => 'Tom', 'age' => 22 ]; echo json_encode($data); // 输出 {"name":"Tom","age":22}
In the above example, first define a function containing name
and age
An associative array of two key-value pairs$data
. Next, use the json_encode()
function to convert $data
into a JSON string and output it.
It should be noted that when PHP objects and arrays are converted into JSON strings, Chinese will be escaped into Unicode encoding by default. You can avoid Chinese escaping by setting the JSON_UNESCAPED_UNICODE
constant. At the same time, you can also set the indentation and space symbols of the output format.
The following are common optional parameters of the json_encode()
function:
JSON_PRETTY_PRINT
Make the output format indented and make writing more friendly .JSON_UNESCAPED_UNICODE
Do not escape Chinese characters.JSON_UNESCAPED_SLASHES
Do not escape slashes.JSON_NUMERIC_CHECK
Convert string numbers to numeric types.JSON_FORCE_OBJECT
Convert the array to object output, ensuring that the returned object must be in object form.
The above parameters can be used in combination, for example:
$data = [ 'name' => 'Tom', 'age' => 22 ]; echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
In the above example, the two parameters JSON_PRETTY_PRINT
and JSON_UNESCAPED_UNICODE
Used in combination, the output format is indented and does not escape Chinese.
4. Summary
In PHP, using JSON format for data interaction has become one of the most common practices. This article starts from the concept of JSON and introduces the method of parsing and generating JSON in PHP. Developers can choose the appropriate method to implement JSON operations based on actual needs. Understanding the relevant knowledge of JSON will help us better interact with front-end and back-end data and improve the development efficiency of web applications.
The above is the detailed content of A guide to JSON parsing and generation in PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

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

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,

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

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.

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.
