In the process of developing web applications, data in JSON (JavaScript Object Notation) format has become a common exchange format. Therefore, for applications that obtain JSON data through APIs, converting it into a PHP array is an essential operation. In this article, we will explore how to convert JSON data obtained from API into PHP array.
Before explaining how to convert JSON data into a PHP array, we need to understand what JSON is. JSON is a lightweight data exchange format extended from JavaScript object literals. When it comes to transferring data, JSON is generally faster, easier to parse, and easier to use than XML.
JSON data is usually represented in the form of key/value pairs, where the key is a string and the value can be a string, number, Boolean value, null, array, or object. The following is an example of a JSON object:
{ "name": "John Doe", "age": 30, "isMarried": false, "hobbies": ["reading", "traveling", "sports"], "address": { "city": "New York", "state": "NY" } }
Before getting JSON data, you should determine the API for the required data and ensure that the API Have appropriate access rights. For this article, we will use the following sample API:
https://jsonplaceholder.typicode.com/posts/1
This API returns JSON data about post 1 as shown below:
{ "userId": 1, "id": 1, "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto" }
It can be read from the API using PHP's "file_get_contents" function Take the JSON data and store it in a variable like this:
$url = 'https://jsonplaceholder.typicode.com/posts/1'; $json = file_get_contents($url);
To convert JSON data to PHP Array, using PHP's built-in "json_decode" function. This function converts JSON formatted data into a PHP array or object. The following is an example of converting the above JSON data to a PHP array:
$url = 'https://jsonplaceholder.typicode.com/posts/1'; $json = file_get_contents($url); $array = json_decode($json, true);
In this example, the second parameter of the "json_decode" function is set to "true" in order to convert the JSON data to a PHP array without Not an object. Store the returned array in "$array".
JSON data can now be accessed by referencing individual elements in the array. The following is an example of printing the value of the "title" key in an array:
echo $array['title'];
By converting JSON data to a PHP array, it can be easily used in web applications process and use data. JSON data can be easily converted into PHP arrays using PHP's built-in "json_decode" function.
The above is the detailed content of How to convert JSON data from API to PHP array. For more information, please follow other related articles on the PHP Chinese website!