Home Backend Development PHP Problem PHP adds, deletes and modifies json files

PHP adds, deletes and modifies json files

May 24, 2023 pm 03:10 PM

With the development of the Internet, data interaction becomes more and more frequent, among which JSON (JavaScript Object Notation) has become one of everyone’s favorite data transmission formats. Therefore, processing JSON data is becoming increasingly important. This article will introduce the use of PHP to process the addition, deletion, modification, and search operations of JSON files.

  1. The grammatical basis of JSON

Before formally explaining the operation of JSON by PHP, first understand the grammatical basis of JSON. JSON uses key-value pairs to record data, where the key is enclosed in double quotes, followed by a colon, and then a value (can be any type of value, such as: string, number, Boolean value, array, object , null). Multiple key-value pairs are separated by commas, and the entire JSON is surrounded by braces {}.

For example:

{

"name": "张三",
"age": 25,
"city": "上海",
"friends": [
    "李四",
    "王五",
    "赵六"
]
Copy after login
Copy after login

}

  1. JSON function in PHP

PHP built-in There are some functions for processing JSON data, including:

json_encode(): used to convert PHP arrays into JSON format strings.

json_decode(): used to convert JSON format string to PHP array/object.

json_last_error(): used to obtain the error information generated by the last JSON encoding/decoding.

The following will introduce the specific use of these functions through examples.

  1. Reading and parsing JSON files

We assume that there is a JSON file data.json with the following content:

{

"name": "张三",
"age": 25,
"city": "上海",
"friends": [
    "李四",
    "王五",
    "赵六"
]
Copy after login
Copy after login

}

We need to read this JSON file and parse it into a PHP array, just use the json_decode() function, the code is as follows:

// 读取JSON文件
$json_str = file_get_contents('data.json');

// 解析JSON文件为PHP数组
$data = json_decode($json_str, true);

// 打印数组
print_r($data);
Copy after login

?>

The output result is as follows:

Array
(

[name] => 张三
[age] => 25
[city] => 上海
[friends] => Array
    (
        [0] => 李四
        [1] => 王五
        [2] => 赵六
    )
Copy after login

)

Among them, the second parameter of the json_decode() function is true, indicating decoding into a PHP array. If this parameter is not passed or false is passed, it will be decoded into a PHP object.

  1. Writing and generation of JSON files

In PHP, you can use the json_encode() function to convert a PHP array into a string in JSON format. For example, to convert the array $data in the above example into a string in JSON format, the code is as follows:

// 将PHP数组转换为JSON格式字符串
$json_str = json_encode($data, JSON_UNESCAPED_UNICODE);

// 打印JSON格式字符串
echo $json_str;
Copy after login

?>

The output result is as follows :

{"name":"Zhang San","age":25,"city":"Shanghai","friends":["李四","王五","Zhao Liu" ]}

As you can see, the second parameter JSON_UNESCAPED_UNICODE of the json_encode() function means not to escape Chinese into Unicode encoding.

Next, we need to write the above JSON format string into a file. You can use the file_put_contents() function. The code is as follows:

// 将JSON格式字符串写入文件
file_put_contents('result.json', $json_str);
Copy after login

?>

The first parameter is the saved file name, and the second parameter is the JSON format string to be written.

  1. JSON file modification

Modifying the JSON file actually means modifying its corresponding PHP array, and then converting the array into a JSON format string, overwriting the original Just file. Suppose we want to change Zhang San’s age to 30 years old. The code is as follows:

// 修改PHP数组
$data['age'] = 30;

// 将PHP数组转换为JSON格式字符串
$json_str = json_encode($data, JSON_UNESCAPED_UNICODE);

// 覆盖原来的JSON文件
file_put_contents('data.json', $json_str);
Copy after login

?>

  1. Deletion of JSON files

To delete JSON files, you can use the unlink() function, as follows:

// 删除JSON文件
unlink('data.json');
Copy after login

?>

  1. Query of JSON data

When processing data in JSON, we often need to query the value of a certain key. If you need to query Zhang San's city, the code is as follows:

// 读取JSON文件
$json_str = file_get_contents('data.json');

// 解析JSON文件为PHP数组
$data = json_decode($json_str, true);

// 查询张三的城市
$city = $data['city'];

// 打印张三的城市
echo $city;  // 上海
Copy after login

?>

As you can see from this example, JSON data is processed in PHP There is no difference from dealing with ordinary arrays or objects.

Summary

This article introduces the addition, deletion, modification and query operations of PHP on JSON files, including reading and parsing, writing and generating, modifying, deleting and querying. Of course, these operations are based on JSON files or strings, not databases. Therefore, when we need to process large amounts of data, it is recommended to use a database instead of JSON files.

The above is the detailed content of PHP adds, deletes and modifies json files. 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

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)

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. Mar 25, 2025 am 10:37 AM

PHP 8's JIT compilation enhances performance by compiling frequently executed code into machine code, benefiting applications with heavy computations and reducing execution times.

PHP Secure File Uploads: Preventing file-related vulnerabilities. PHP Secure File Uploads: Preventing file-related vulnerabilities. Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Encryption: Symmetric vs. asymmetric encryption. PHP Encryption: Symmetric vs. asymmetric encryption. Mar 25, 2025 pm 03:12 PM

The article discusses symmetric and asymmetric encryption in PHP, comparing their suitability, performance, and security differences. Symmetric encryption is faster and suited for bulk data, while asymmetric is used for secure key exchange.

PHP Authentication & Authorization: Secure implementation. PHP Authentication & Authorization: Secure implementation. Mar 25, 2025 pm 03:06 PM

The article discusses implementing robust authentication and authorization in PHP to prevent unauthorized access, detailing best practices and recommending security-enhancing tools.

PHP API Rate Limiting: Implementation strategies. PHP API Rate Limiting: Implementation strategies. Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP CSRF Protection: How to prevent CSRF attacks. PHP CSRF Protection: How to prevent CSRF attacks. Mar 25, 2025 pm 03:05 PM

The article discusses strategies to prevent CSRF attacks in PHP, including using CSRF tokens, Same-Site cookies, and proper session management.

PHP Input Validation: Best practices. PHP Input Validation: Best practices. Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

See all articles