Home Backend Development PHP Tutorial A guide to JSON parsing and generation in PHP

A guide to JSON parsing and generation in PHP

Jun 11, 2023 am 10:57 AM
php json parsing json generated

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"]
}
Copy after login

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
Copy after login

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
Copy after login

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}
Copy after login

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);
Copy after login

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!

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

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

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

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

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

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

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,

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

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.

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.

See all articles