Sitemap / Advertise

Information



Tags



Share

How to get information from an external JSON file in PHP

Advertisement:


read_later

Read Later

Keywords



Keywords



read_later

Read Later

Information

Tags

Share





Advertisement

Advertisement




Definition

In this tutorial, I will show you how to get data packets from an external server or page to your existing server as JSON objects. In that way, you will be able to collect any information from any page in PHP as long as the external source is a JSON file.

Code

First of all, define the external source(JSON file) as a domain address or a different page in the same server.

Get the information by using file_get_content($_external_source).

The incoming data from the external source is encoded as a JSON object and therefore should be decoded as a PHP object by using json_decode($content, TRUE).

Save information as a PHP object for further usage.

------------JSON File(code_demo.json)----------------
{"Books":[{"id":"001","name":"To Kill a Mockingbird","author":"Harper Lee"},{"id":"002","name":"The Count of Monte Cristo","author":"Alexandre Dumas"},{"id":"003","name":"The Secret Life of Bees","author":"Sue Monk Kidd"}],"Cars":[{"id":"001","name":"fiat","date":"1997"}]}

------------PHP Code----------------
$_external_source = "https://www.theamplituhedron.com/articles/How-to-get-information-from-an-external-JSON-file-in-PHP/code_demo.json";

$content = file_get_contents($_external_source);

$decoded_content = json_decode($content, TRUE);

$information = $decoded_content;

$data_1 = $information['Books'][1]['name'];
$data_2 = $information['Cars'][0]['name'];

Result:

Data from code_demo.json :

Data_1 => The Count of Monte Cristo

Data_2 => fiat