Read a JSON file with php

Json file, how to read it using php?

Most importantly, get the JSON content using file_get_contents() and to not avoid warnings specify the sources:

To read the file with an http request specify http/https:

$jsonData = file_get_contents('http://www.sitename.io/data/jsondata.JSON');

To read the file form the filesystem:

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

decode the JSON using 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 the database name of databaseOne:

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

Use this code to loop through the array:

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

This is an example to show how to print the database name for each entries:

foreach ($$data as $content) {
        if($content) {
            foreach ($content as $key => $value) {
                if ($key === 'dbname'){
                    echo ($value . '</br>');
                }
            }
        }
    }