Home  >  Article  >  Backend Development  >  Convert php json data to array

Convert php json data to array

王林
王林Original
2023-05-23 11:14:36368browse

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