search
HomeBackend DevelopmentPHP ProblemPHP adds, deletes and modifies json files

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": [
    "李四",
    "王五",
    "赵六"
]

}

  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": [
    "李四",
    "王五",
    "赵六"
]

}

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);

?>

The output result is as follows:

Array
(

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

)

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;

?>

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);

?>

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);

?>

  1. Deletion of JSON files

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

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

?>

  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;  // 上海

?>

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
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
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

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 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.

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 Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

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 XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools