Read a JSON file using php

May 28, 2015

JSON
php
arrays
backend

Get JSON content using filegetcontents

To get the data from a url:

$jsonData = file_get_contents('https://www.example.com/data/dataset.JSON');

To get the data from the filesystem:

$config = file_get_contents(__DIR__ . '/config.json');

To decode the JSON data we can use json_decode:

$data = json_decode($config, true);

Use var_dump or print_r to understand the data structure. Having this data:

{
  "databaseOne": {
    "dbhost": "localhost:8889",
    "dbname": "dev_db_1",
    "dbusername": "root",
    "dbpassword": "root"
  },
  "databaseTwo": {
    "dbhost": "localhost:8889",
    "dbname": "dev_db_2",
    "dbusername": "root",
    "dbpassword": "root"
  }
}

To print for example the database name of databaseOne:

echo $data['databaseOne']['dbname'];

To loop through the array:

foreach ($data['databaseOne'] as $field => $value) {
    echo $field . ':' . $value . '</br>';
}```

This following example to shows how to print the database name for each entry:
```php
foreach ($$data as $content) {
	if($content) {
		foreach ($content as $key => $value) {
		if ($key === 'dbname'){
			echo ($value . '</br>');
			}
		}
	}
}

Written by huckbit web developer who lives and works in UK building cool things. You can find me on twitter.