search
HomeBackend DevelopmentPHP ProblemConvert php json data to array
Convert php json data to arrayMay 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:

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

$arr = json_decode($json, true);

var_dump($arr);

Output result:

array(3) {
  ["name"]=>
  string(3) "Tom"
  ["age"]=>
  string(2) "20"
  ["sex"]=>
  string(4) "male"
}

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:

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

$obj = json_decode($json);

var_dump($obj);

Output result:

object(stdClass)#1 (3) {
  ["name"]=>
  string(3) "Tom"
  ["age"]=>
  string(2) "20"
  ["sex"]=>
  string(4) "male"
}

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:

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

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:

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

Output result:

JSON 数据存在语法错误
NULL

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:

// 首先,安装 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);

Output result:

array(2) {
  ["name"]=>
  string(3) "Tom"
  ["age"]=>
  int(20)
}

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:

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

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

echo $json;

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
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
How to Implement message queues (RabbitMQ, Redis) in PHP?How to Implement message queues (RabbitMQ, Redis) in PHP?Mar 10, 2025 pm 06:15 PM

This article details implementing message queues in PHP using RabbitMQ and Redis. It compares their architectures (AMQP vs. in-memory), features, and reliability mechanisms (confirmations, transactions, persistence). Best practices for design, error

What Are the Latest PHP Coding Standards and Best Practices?What Are the Latest PHP Coding Standards and Best Practices?Mar 10, 2025 pm 06:16 PM

This article examines current PHP coding standards and best practices, focusing on PSR recommendations (PSR-1, PSR-2, PSR-4, PSR-12). It emphasizes improving code readability and maintainability through consistent styling, meaningful naming, and eff

How Do I Work with PHP Extensions and PECL?How Do I Work with PHP Extensions and PECL?Mar 10, 2025 pm 06:12 PM

This article details installing and troubleshooting PHP extensions, focusing on PECL. It covers installation steps (finding, downloading/compiling, enabling, restarting the server), troubleshooting techniques (checking logs, verifying installation,

How to Use Reflection to Analyze and Manipulate PHP Code?How to Use Reflection to Analyze and Manipulate PHP Code?Mar 10, 2025 pm 06:12 PM

This article explains PHP's Reflection API, enabling runtime inspection and manipulation of classes, methods, and properties. It details common use cases (documentation generation, ORMs, dependency injection) and cautions against performance overhea

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.

How to Use Asynchronous Tasks in PHP for Non-Blocking Operations?How to Use Asynchronous Tasks in PHP for Non-Blocking Operations?Mar 10, 2025 pm 04:21 PM

This article explores asynchronous task execution in PHP to enhance web application responsiveness. It details methods like message queues, asynchronous frameworks (ReactPHP, Swoole), and background processes, emphasizing best practices for efficien

How to Use Memory Optimization Techniques in PHP?How to Use Memory Optimization Techniques in PHP?Mar 10, 2025 pm 04:23 PM

This article addresses PHP memory optimization. It details techniques like using appropriate data structures, avoiding unnecessary object creation, and employing efficient algorithms. Common memory leak sources (e.g., unclosed connections, global v

How Do I Stay Up-to-Date with the PHP Ecosystem and Community?How Do I Stay Up-to-Date with the PHP Ecosystem and Community?Mar 10, 2025 pm 06:16 PM

This article explores strategies for staying current in the PHP ecosystem. It emphasizes utilizing official channels, community forums, conferences, and open-source contributions. The author highlights best resources for learning new features and a

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

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

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.