You may also want to learn how to form a JSON object in PHP. In this post, we have covered everything you need to know in extracting and accessing a JSON object data using PHP. For such an instance, you can use the foreach() function to loop through all the objects as below: countries If you want to access all the array data then it can be tiresome and time-consuming to write the code for accessing each at a time especially when the object is large. We access the China array object as below: " Įcho "Code: ".$data."" But when accessing the array items, we start counting from 0, hence the index of China in the array is 2. For example, china is in the third position. To access the values of a country in the example above, you just have to know its object position in the array. You may have a large JSON object made of an array of objects, like in the example below: Looping through an object of objects with foreach() You access the data as in any other PHP associative array as in the example below: " Įcho "First Name: ".$data."" Įcho "Email Address: ".$data."" The value is set to false by default if you don't pass it. You can as well convert the JSON object to a PHP associative array by passing a second(optional) parameter in the json_decode() function with the boolean value " true" as below. This is the same as the name in the name-value pair in JSON object eg $data->firstName. To access the PHP object data, you use the object operator ( ->) after the object name, followed by the key of the key-value pair. $json = file_get_contents("php://input") įor instance, the JSON data is sent below as a POST request: string(4) "John" => string(3) "Doe" => string(17) => string(12) "11" } To receive JSON data as a POST request, we use the “php://input” along with the function file_get_contents() as below: In this post, we will cover how to decode a JSON object and access its data in PHP.īelow is an example of a simple JSON object: It is the most popular and lightweight data-interchange format for web applications and the de-facto format for the data exchange in RESTful web services requests and responses. It is easy to generate and parse in many programming languages.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |