Convert a JSON string to array in PHP
This article demonstrates how to convert a JSON string to an array in PHP.
The standard solution to decode a JSON string is to use the json_decode() function, which takes an JSON encoded string and converts it into an appropriate PHP type. The following code snippet shows how to use json_decode() to convert a JSON string into an object. Note that elements within an object are accessed by encapsulating the element within braces and the apostrophe.
|
1 2 3 4 5 6 7 8 9 10 |
<?php $json_str = '{"x":5,"y":6}'; $obj = json_decode($json_str); print '(' . $obj->{'x'} . ', ' . $obj->{'y'} . ')'; /* Output: (5, 6) */ ?> |
If you want the json_decode() function to return an associative array instead of an object, you can set its second parameter to true. The second parameter is optional and is false by default; you have to set it to true to convert the JSON objects into associative arrays. For example,
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php $json_str = '{"x":5,"y":6}'; $obj = json_decode($json_str, true); var_export($obj); /* Output: array ( 'x' => 5, 'y' => 6, ) */ ?> |
If your JSON string is encoded using the htmlentities() or htmlspecialchars() function, you might want to decode the HTML entities back to their corresponding characters before invoking json_decode(). This can be done using the html_entity_decode() function, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php $json_str = '{"x":5,"y":6}'; $decoded_str = html_entity_decode($json_str); $obj = json_decode($decoded_str, true); var_export($obj); /* Output: array ( 'x' => 5, 'y' => 6, ) */ ?> |
That’s all about converting a JSON string to an array in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)