Read file json in php

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 //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 = ; // 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.

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.

  • file_get_contents
  • json_decode

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.

Can PHP read JSON file?

Use file_get_contents[] function to read JSON file into PHP. This function is used to read the file into PHP code. file_name is the name of the file and path is the location to be checked.

How do I extract data from JSON with PHP?

Use json_decode[] Function to Extract Data From JSON in PHP. We will use the built-in function json_decode[] to extract data from JSON. We will convert the JSON string to an object or an array to extract the data. The correct syntax to use this function is as follows.

What is JSON file in PHP?

What is JSON? JSON stands for JavaScript Object Notation, and is a syntax for storing and exchanging data. Since the JSON format is a text-based format, it can easily be sent to and from a server, and used as a data format by any programming language.

How show JSON data from HTML table in PHP?

To use PHP function file_get_contents [] we can read a file and retrieve the data present in JSON file. After retrieving data need to convert the JSON format into an array format. Then with the use of looping statement will display as a table format.

Chủ Đề