How To Read A JSON File Using PHP With Examples

If you weren’t already aware, JSON can come in the format of a file. They are named something like the following – VitalLogicData.json. It’s virtually a text file but contains well-formatted data in the style of JavaScript Object Notation. These files can be read from or, of course, appended too.

The first time I saw the .json file I was pretty confused, I always thought of JSON only belonging within the browser. But there are many reasons for JSON files, so we need to know how to manage them. This article will give you the knowledge to read JSON files with PHP and it’s an ideal tutorial for beginners.

JSON File Data

For this tutorial, I found a repository on GitHub that is perfect. It contains a huge list of color names and their Hex Numbers. You can get the css-color-names.json from the repo here. Or you can download the file directly here.

As you will see in the file, the contents will be laid out like the following snippet –

{
  "aliceblue": "#f0f8ff",
  "antiquewhite": "#faebd7",
  "aqua": "#00ffff",
  "aquamarine": "#7fffd4",
  "azure": "#f0ffff",
  "beige": "#f5f5dc",
  "bisque": "#ffe4c4",
  "black": "#000000",
......
}

Once downloaded, place the file in the root directory of your PHP website environment. For instance http://localhost/css-color-names.json. This will just make it easier to find when we are trying to read the file via PHP.

Read JSON File With PHP Example

In the following example, we will use PHP to read data from the CSS-color-names file. Then when we’ve successfully printed the data to the page, we will then inject the data into JavaScript tags and log it to the console. Let’s get started.

Firstly, we need to read the file contents with PHP’s native function file_get_contents. The first parameter file_get_contents expects is the path to the file that is in need of reading. In this case CSS-color-names.json.

Note that the root directory doesn’t need to be specified, because in this case, the script is within that directory already.

Reading JSON File Contents
// Get the contents of the JSON file 
$strJsonFileContents = file_get_contents("css-color-names.json");
var_dump($strJsonFileContents); // show contents

The above code dumps the following to the page –

string '{
  "aliceblue": "#f0f8ff",
  "antiquewhite": "#faebd7",
  "aqua": "#00ffff",
  "aquamarine": "#7fffd4",
  "azure": "#f0ffff",
  "beige": "#f5f5dc",
  "bisque": "#ffe4c4",
  "black": "#000000",
  "blanchedalmond": "#ffebcd",
  "blue": "#0000ff",
  "blueviolet": "#8a2be2",
  "brown": "#a52a2a",
  "burlywood": "#deb887",
  "cadetblue": "#5f9ea0",
  "chartreuse": "#7fff00",
  "chocolate": "#d2691e",
  "coral": "#ff7f50",
  "cornflowerblue": "#6495ed",
  "cornsilk": "#fff8dc",
  "crimson": "#dc143c",
  "cyan": '... (length=3841)

I know what your thinking, is it really that simple? Well, virtually yes, but, in order for it to become useful, we need to pass it into some JavaScript or convert it to a PHP array. I’ll do both in the following examples.

Converting JSON File Contents To PHP Array

A JSON string in PHP is pretty useless, so if we convert it to an array, we can then loop over it and do some funky stuff with the data. You may want to store it in a database or print it does an HTML table. Whatever you want to do, it will need parsing as an array first. To do this, we use json_decode with its a brilliant Boolean parameter to convert to an associative array.

// Get the contents of the JSON file 
$strJsonFileContents = file_get_contents("css-color-names.json");
// Convert to array 
$array = json_decode($strJsonFileContents, true);
var_dump($array); // print array

The PHP code here will print the full associative array to the page like follows –

array (size=148)
  'aliceblue' => string '#f0f8ff' (length=7)
  'antiquewhite' => string '#faebd7' (length=7)
  'aqua' => string '#00ffff' (length=7)
  'aquamarine' => string '#7fffd4' (length=7)
  'azure' => string '#f0ffff' (length=7)
.......

This now means we can easily access each of the colors by their specified names and return the Hexadecimal value that can be used in CSS, for example. Using the following code, we can request the aqua hex color from the array. This, of course, opens new windows of opportunity for the application.

echo $arrayJsonColors["aqua"]; // outputs #00ffff
Injecting JSON Into JavaScript

Nine times out of ten, working with JavaScript Object Notation means you will most likely need it for some JavaScript functionality. This is why I wanted to quickly show how to inject the data directly into a JavaScript variable using PHP. It’s pretty simple to do.

By using PHP within the script tags, we can echo the data whilst defining a JavaScript variable. In turn, the JSON will be parsed and be ready to use. See the following example –

var colorsJson = <?php echo $strJsonFileContents; ?>; // Pass in json from PHP
console.info(colorsJson); // Log to console.
console.log(colorsJson.aqua); // Log single value to console.

The screenshot below shows the console output in Chrome. The JSON has been correctly parsed and is now available to access the properties with dot notation.

console output json file contents

References

Throughout the examples, within this article, some native PHP functions were used to read a JSON file. Below is the link’s direct to those function’s documentation on the PHP website. Check them out for reference.

Summary

In this tutorial, we learned that you can read JavaScript Object Notation files directly in PHP. It’s more than capable of doing so and can even parse it for further usage, as shown when converted to an array. Also, passing the data directly into JavaScript was explained, giving you the tools to then build things like visualizations or passing into an ajax call.

SHARE ON

The Author: Dan Englishby

How To Read A JSON File Using PHP With Examples
Posted in PHP

You May Also Like

Leave a Reply

Your email address will not be published.