Home Backend Development PHP Problem How to convert JSON data to array in PHP

How to convert JSON data to array in PHP

Apr 19, 2023 am 11:40 AM

During the development process, we often encounter the need to convert data in JSON format into PHP arrays. This need is very common when interacting with the front end, receiving data from other system interfaces, etc. This article will introduce how to convert JSON data to PHP array in PHP.

  1. PHP built-in function json_decode()

PHP has a built-in function json_decode(), which can convert a JSON format string into a PHP array. The following is an example of using the json_decode() function:

$json = '{"name":"john","age":30,"city":"New York"}';
$array = json_decode($json, true);

print_r($array);
Copy after login

The output result is:

Array
(
    [name] => john
    [age] => 30
    [city] => New York
)
Copy after login

In the above example, $json is a string in JSON format, and $array is using json_decode( ) function converts $json into a PHP array. It should be noted that the second parameter of the json_decode() function must be true, which means converting the converted JSON object into a PHP array.

  1. Parsing JSON containing Chinese

When processing JSON data containing Chinese, we need to pay attention to the problem of character encoding, otherwise we may encounter errors during the conversion process .

Suppose there is a JSON string containing Chinese, as shown below:

$json = '{"name":"张三","age":30}';
Copy after login

When the above code is used to convert the JSON string into a PHP array, a Notice error will be generated, prompting "json_decode(): Input string contains invalid UTF-8 characters" (JSON string contains invalid UTF-8 characters).

This is because the json_decode() function only supports UTF-8 encoding by default, and the Chinese characters in the JSON string are encoded in GBK or other encoding methods, so we need to convert them to UTF- 8 encoding, and then JSON conversion.

Use the PHP built-in function iconv() to convert the string from GBK to UTF-8 encoding:

$json = '{"name":"张三","age":30}';
$json_utf8 = iconv('GBK', 'UTF-8//IGNORE', $json);

$array = json_decode($json_utf8, true);

print_r($array);
Copy after login

The result output is:

Array
(
    [name] => 张三
    [age] => 30
)
Copy after login
  1. JSON data Verification

When converting JSON data, sometimes we need to verify it to ensure that it conforms to our expected structure and format.

PHP has a built-in function json_last_error() that can obtain the error code generated by the last JSON conversion operation. We can judge whether the JSON data meets expectations based on the error code.

For example, the following code demonstrates how to determine whether an illegal JSON string is as expected when converting it:

$json = '{"name":"john","age":30,},
    {"name":"mike","age":32}';
$array = json_decode($json, true);

if (json_last_error() === JSON_ERROR_NONE) {
    echo 'JSON 格式正确';
} else {
    echo 'JSON 格式错误';
}
Copy after login

In the above code, $json contains two JSON Objects, not separated by commas, are JSON format errors. Therefore, the json_last_error() function returns JSON_ERROR_SYNTAX, indicating a JSON syntax error.

  1. Readability of JSON data

When processing JSON data, in order to facilitate debugging and reading, we can also add indentation and line breaks to the JSON data. Make it easier to read.

PHP’s built-in function json_encode() can convert a PHP array into a more readable JSON format string. For example:

$array = [
    'name' => 'john',
    'age' => 30,
    'city' => 'New York'
];

$json = json_encode($array, JSON_PRETTY_PRINT);

echo $json;
Copy after login

The output result is:

{
    "name": "john",
    "age": 30,
    "city": "New York"
}
Copy after login

In the above code, after we convert $array into a string in JSON format, we pass a JSON_PRETTY_PRINT parameter, which means that the JSON string will be Indentation and line breaks are handled to improve its readability.

It should be noted that the parameter JSON_PRETTY_PRINT in the json_encode() function is only supported in PHP version 5.4 and above.

Summary

In PHP, we can use the built-in function json_decode() to convert a JSON-formatted string into a PHP array. When processing JSON data containing Chinese, you need to pay attention to character encoding issues; when converting JSON data, you need to verify whether it meets expectations; when generating JSON data, you can use the json_encode() function to optimize its readability.

The above is the method of converting JSON to PHP array. I hope it will be helpful to you in actual development.

The above is the detailed content of How to convert JSON data to array 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

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks 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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24