Php json decode from url

How to extract and access JSON data in PHP

JavaScript Object Notation(JSON) is a lightweight human-readable text format for storing and transporting data consisting of name-value pairs and arrays.

It is easy to generate and parse in many programming languages. 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.

In this post, we will cover how to decode a JSON object and access its data in PHP.

Below is an example of a simple JSON object:

How to receive JSON data in PHP

1. From a POST or GET request

To receive JSON data as a POST request, we use the “php://input” along with the function file_get_contents() as below:

For instance, the JSON data is sent below as a POST request:

'; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $payload); curl_exec($curl); curl_close($curl); 

To receive the above request data in the register.php file, just add file_get_contents(«php://input») and assign it to a variable for processing eg:

2. Reading a JSON file

A JSON file contains a JSON object and has a file extension of .json. You can as well open the file in PHP and access its data.

Similar to POST or GET request, we use file_get_contents() but instead of having “php://input”, we use the file path.

For example, if we have a JSON file with path «https://www.example.com/mydata.json«, we can access its data as below:

If the json file and the PHP file accessing it are in the same website, we can use relative path instead of the full file URL.

Extracting/Decoding JSON data in PHP

We use the built-in function json_decode() to convert the JSON string to the appropriate data type such as an object or an array.

1. Accessing JSON data as a PHP object

By default the json_decode() function returns an object.

Example
The example below decodes a JSON object into a PHP object:

'; $data = json_decode($json); var_dump($data); 

The above example outputs below:

object(stdClass)#1 (4) < ["firstName"]=>string(4) «John» [«lastName»]=> string(3) «Doe» [«email»]=> string(17) «johndoe@gmail.com» [«phone»]=> string(12) «111-111-1111» >

To access the PHP object data, you use the object operator (->) after the object name, followed by the key of the key-value pair. This is the same as the name in the name-value pair in JSON object eg $data->firstName .

'; $data = json_decode($json); echo "My name is".$data->firstName." ".$data->lastName; //Output: My name is John Doe 

2. Accessing JSON data as an array

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. The value is set to false by default if you don’t pass it.

Читайте также:  Coding standards for html

The example below decodes JSON object into a PHP associative array:

'; $data = json_decode($json, true); var_dump($data); 

The above example outputs below:

array(4) < ["firstName"]=>string(4) «John» [«lastName»]=> string(3) «Doe» [«email»]=> string(17) «johndoe@gmail.com» [«phone»]=> string(12) «111-111-1111» >

You access the data as in any other PHP associative array as in the example below:

'; $data = json_decode($json, true); echo "My name is ".$data["firstName"]." ".$data["lastName"]; //Output: My name is John Doe 

3. Accessing data in a nested JSON object

A JSON object may comprise of json objects and arrays as the values in its name-value pairs such as in the example below:

In the above example, the «address» has an object as its value while «siblings» has an array value comprising of objects.

The easiest way of accessing all the data is decoding the object as an associative array.

, "siblings": [ < "name": "Joseph Doe" >, < "name": "Mary Doe" >] >'; $data = json_decode($json, true); //Displaying all the data echo "First Name: ".$data["firstName"]."
"; //Output -> First Name: John echo "First Name: ".$data["lastName"]."
"; //Output -> Last Name: Doe echo "Email Address: ".$data["email"]."
"; //Output -> Email Address: johndoe@gmail.com echo "Postal Address: ".$data["address"]["postalAddress"]."
"; //Output -> Postal Address: 12345 echo "Postal Code: ".$data["address"]["postalCode"]."
"; //Output -> Postal Code: 5432 echo "City: ".$data["address"]["city"]."
"; //Output -> City: Nairobi echo "Sibling 1: ".$data["siblings"][0]["name"]."
"; //Output -> Sibling 1: Joseph Doe echo "Sibling 2: ".$data["siblings"][1]["name"]."
"; //Output -> Sibling 2: Mary Doe

Looping through an object of objects with foreach()

You may have a large JSON object made of an array of objects, like in the example below:

To access the values of a country in the example above, you just have to know its object position in the array. For example, china is in the third position. But when accessing the array items, we start counting from 0, hence the index of China in the array is 2.

We access the China array object as below:

"; //Output -> Country: China echo "Code: ".$data["countries"][2]["code"]."
"; //Output -> Code: CN echo "City: ".$data["countries"][2]["city"]."
"; //Output -> City: Beijing

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. For such an instance, you can use the foreach() function to loop through all the objects as below:

, < "name": "India", "code": "IN", "city": "New Delhi" >, < "name": "China", "code": "CN", "city": "Beijing" >, < "name": "Germany", "code": "DE", "city": "Berlin" >, < "name": "Kenya", "code": "KE", "city": "Nairobi" >] >'; $countries = json_decode($json)->countries; foreach($countries as $country)< echo "Country: ".$country->name."
"; echo "Code: ".$country->code."
"; echo "City: ".$country->city."
"; >

Conclusion

In this post, we have covered everything you need to know in extracting and accessing a JSON object data using PHP.

Читайте также:  (.*?)

If you want to get notified via email when we add more incredible content to our blog, kindly subscribe to our email newsletter.

Источник

Get JSON from URL in PHP

In this tutorial, I’m going to show you how to get json from url in php script. JSON has become a popular way to exchange data and web services outputs in json format. To send a HTTP request and parse JSON response from URL is fairly simple in php but newbies may find how to parse json difficult.

Let’s see how to build a php json parser script. For this script, I’m going to access Google MAP web service via API and get latitude and longitude co-ordinates for a location. Google map api produces both json/xml output. But for this example I’m going to get the json response and show you how to parse json object to retrieve the geo-metric details.

php-get-json-from-url

How to Get JSON from URL in PHP

This is the php script to read the json data from url.

results[0]->geometry->location->lat; $lng = $json->results[0]->geometry->location->lng; echo "Latitude: " . $lat . ", Longitude: " . $lng; // output // Latitude: 40.6781784, Longitude: -73.9441579 ?>

The above php script sends a HTTP request to Google MAP web service along with a parameter containing a physical address. The API in turn returns the geometric co-ordinates for the address as json string — which we further decode into a php object and parse it to retrieve the latitude and longitude details.

The php function file_get_contents($url) send a http request to the provided url and returns json data.

The function json_decode($json) decodes the provided json string and returns as a PHP object.

As simple as that you can parse json response. That was all about getting json from url in php.

Источник

Get JSON Object From URL in PHP

Get JSON Object From URL in PHP

  1. Use the file_get_contents() Function to Get JSON Object From the URL in PHP
  2. Use curl to Get JSON Object From the URL in PHP

This tutorial introduces how to get the JSON object from a URL in PHP.

Use the file_get_contents() Function to Get JSON Object From the URL in PHP

We can use file_get_contents() along with json_decode() to get the JSON object from a URL. The file_get_contents() function reads the file in a string format. We should specify the path to the file in the function or we can even give the URL in the function as the first parameter. We should enable allow_url_fopen to use the file_get_contents() function. We can enable it by setting phpini_set(«allow_url_fopen», 1) in the php.ini file. The json_decode() function converts the JSON object into PHP object. Thus, we can access the objects in JSON URL as PHP objects.

Читайте также:  Convert bytes to float python

For the demonstration, we will use a dummy JSON URL from jsonplaceholder. Create a variable $url and store the URL in it. Use the URL https://jsonplaceholder.typicode.com/posts/1 . The JSON objects of the URL are shown below. Next, create a $json variable and use the $url as an argument to the file_get_contents() function. Now, use the json_decode() function to decode JSON string to PHP object. Store the object in the $jo variable. Lastly, access the title object with $jo and print it out.

Thus, we accessed a URL containing a JSON object from the web and converted it into PHP. In this way, we can get JSON objects from a URL in PHP.

  "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" > 
php $url = 'https://jsonplaceholder.typicode.com/posts/1'; $json = file_get_contents($url); $jo = json_decode($json); echo $jo->title; ?> 
sunt aut facere repellat provident occaecati excepturi optio reprehenderit 

Use curl to Get JSON Object From the URL in PHP

curl is a command-line tool that is used to send and receive data and files. It uses supported protocols like HTTP, HTTPS, FTP, etc., and sends data from or to a server. In PHP, there is a curl library that lets us make an HTTP request. We can use curl to read file contents from the web. There are various curl functions in PHP that facilitate us to send and receive data. We can use them to get JSON objects from a URL. The curl_init() function initiates the curl. We can use the curl_setopt() function to set several options like returning transfer and setting URLs. The curl_exec() function executes the operation and curl_close() closes the curl.

We can use the same URL as in the first method to demonstrate the use of curl . Create a variable $curl and initiate the curl with the curl_init() function. Set the CURLOPT_RETURNTRANSFER option true using the curl_setopt() function. Next, set the URL using the CURLOPT_URL option. Execute the curl with curl_exec() function with $curl in the parameter and store it in $res variable. Use the curl_close() function to close the $curl variable. Next, use the json_decode() function to change the JSON object to PHP object and display the title object.

Thus, we can get the JSON object from a URL using curl .

php  $curl= curl_init();  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  curl_setopt($curl, CURLOPT_URL, 'https://jsonplaceholder.typicode.com/posts/1';  $res = curl_exec($curl);  curl_close($curl);  $jo = json_decode($res);  echo $jo->title; ?> 
sunt aut facere repellat provident occaecati excepturi optio reprehenderit 

Subodh is a proactive software engineer, specialized in fintech industry and a writer who loves to express his software development learnings and set of skills through blogs and articles.

Related Article — JSON Object

Источник

Оцените статью