Home Backend Development PHP Problem Convert php json data to array

Convert php json data to array

May 23, 2023 am 11:14 AM

In PHP, sometimes we need to convert JSON data into array format for processing. At this time, we can use the json_decode() function to convert JSON data into a PHP array. This article will introduce how to use the json_decode() function to convert JSON data into an array and answer some common questions.

JSON is a lightweight data exchange format that is widely used to transmit data due to its advantages of being simple to understand, easy to use, and easy to extend. PHP is a weakly typed programming language that is efficient, fast, easy to learn and use. Since JSON format is natively supported in PHP, it is very convenient to use PHP to process JSON data during development.

Use json_decode() function to convert JSON data into an array

The following is a sample code to convert a JSON data into an array:

1

2

3

4

5

$json = '{"name":"Tom","age":"20","sex":"male"}';

 

$arr = json_decode($json, true);

 

var_dump($arr);

Copy after login

Output result:

1

2

3

4

5

6

7

8

array(3) {

  ["name"]=>

  string(3) "Tom"

  ["age"]=>

  string(2) "20"

  ["sex"]=>

  string(4) "male"

}

Copy after login

As you can see, the json_decode() function converts JSON data into a PHP array. The second parameter of this function can be set to true or false, which returns an associative array when set to true, or an object when set to false or unset.

The following is a sample code to return an object:

1

2

3

4

5

$json = '{"name":"Tom","age":"20","sex":"male"}';

 

$obj = json_decode($json);

 

var_dump($obj);

Copy after login

Output result:

1

2

3

4

5

6

7

8

object(stdClass)#1 (3) {

  ["name"]=>

  string(3) "Tom"

  ["age"]=>

  string(2) "20"

  ["sex"]=>

  string(4) "male"

}

Copy after login

When parsing a JSON string, if it is found that the character encoding is not UTF-8, it needs to be converted Into UTF-8 encoding:

1

2

3

4

5

6

7

$json = '{"name":"Tom","age":"20","sex":"male"}';

 

$json = mb_convert_encoding($json, 'UTF-8', 'auto'); // 将编码转换为 UTF-8

 

$arr = json_decode($json, true);

 

var_dump($arr);

Copy after login

FAQ

1. How to deal with JSON parsing errors?

During the process of processing JSON data, parsing errors may occur due to problems with the JSON data format or encoding format. At this point, you can use the json_last_error() function to get the cause of the parsing error. This function returns a number representing the type of JSON parsing error. The following is the definition of the error type:

  • JSON_ERROR_NONE: No error, parsing successful.
  • JSON_ERROR_DEPTH: The JSON data is too complex and exceeds the set maximum depth.
  • JSON_ERROR_STATE_MISMATCH: The JSON data format is incorrect.
  • JSON_ERROR_CTRL_CHAR: There is an incorrect control character.
  • JSON_ERROR_SYNTAX: There is a syntax error in the JSON data.
  • JSON_ERROR_UTF8: The JSON data is not UTF-8 encoded.

Use the following code to obtain the cause of the parsing error:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

$json = '{"name": "Tom""age": "20"}'; // 注意,这里有错误

 

$arr = json_decode($json, true);

 

if (json_last_error() !== JSON_ERROR_NONE) {

    switch (json_last_error()) {

        case JSON_ERROR_DEPTH:

            echo 'JSON 数据过于复杂,超出了设置的最大深度';

            break;

        case JSON_ERROR_STATE_MISMATCH:

            echo 'JSON 数据格式不正确';

            break;

        case JSON_ERROR_CTRL_CHAR:

            echo 'JSON 数据中有不正确的控制字符';

            break;

        case JSON_ERROR_SYNTAX:

            echo 'JSON 数据存在语法错误';

            break;

        case JSON_ERROR_UTF8:

            echo 'JSON 数据不是 UTF-8 编码';

            break;

        default:

            echo '未知的 JSON 解析错误';

            break;

    }

}

 

var_dump($arr);

Copy after login

Output result:

1

2

JSON 数据存在语法错误

NULL

Copy after login

As shown above, the json_last_error() function can easily obtain the parsing error to quickly find the problem.

2. How to deal with the problem of non-standard JSON format?

In actual use, some JSON data may not be in the most standardized format, such as the use of a comma after the last attribute value. If you use the json_decode() function to parse this JSON data, NULL will be returned. At this point, we can use a third-party library for processing.

The following is a sample code that uses the json5 library to process JSON non-standard format:

1

2

3

4

5

6

7

8

9

10

11

12

// 首先,安装 json5 库

// composer require symfony/polyfill-mbstring

// composer require webonyx/json5

 

$json = '{"name": "Tom", "age": 20, }'; // 注意,这里有错误

 

use Json5Parser;

 

$parser = new Parser();

$arr = $parser->decode($json);

 

var_dump($arr);

Copy after login

Output result:

1

2

3

4

5

6

array(2) {

  ["name"]=>

  string(3) "Tom"

  ["age"]=>

  int(20)

}

Copy after login

As shown above, it can be easily processed using the json5 library Issues with JSON non-standard format.

3. How to deal with the problem of cross-domain access of JSON data?

The problem of cross-domain access of JSON data means that for security reasons, the browser prohibits the front-end from accessing resources in other domains across ajax requests. At this time, we need to make some settings.

The following is a sample code for using PHP to achieve cross-domain access:

1

2

3

4

5

6

header('Access-Control-Allow-Origin: *'); // 允许所有域名访问

header('Content-Type: application/json');

 

$json = '{"name": "Tom", "age": 20, "sex": "male"}';

 

echo $json;

Copy after login

As shown above, setting the Access-Control-Allow-Origin header in PHP allows other domain names to be cross-domain access.

Conclusion

So far, we have introduced how to use the json_decode() function to convert JSON data into an array, and how to solve some common problems encountered in processing JSON data. I hope this article can be helpful to everyone.

The above is the detailed content of Convert php json data to array. 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 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 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.

See all articles