read a json file in php

To read a JSON file in PHP, you can use the file_get_contents() function to obtain the contents of the JSON file, and json_decode() function to parse the JSON string into a PHP variable.

Here's an example code snippet:

main.php
$json_file = "example.json";
$json_string = file_get_contents($json_file);
$data = json_decode($json_string, true);
116 chars
4 lines

In the above code, we first specify the path to the JSON file ("example.json") and then use the file_get_contents() function to read the contents of the file into a variable called "$json_string".

We then pass the JSON string to the json_decode() function along with the second parameter set to "true", which tells the function to return an associative array rather than an object. The resulting data is stored in a variable called "$data".

You can then access the data in the JSON file as you would with any other PHP array.

related categories

gistlibby LogSnag