New to our community ?

Discover a world of possibilities! Join us and explore a vibrant community where ideas flourish and connections thrive.

One of Our Valued Members

Thank you for being part of our community. Your presence enriches our shared experiences. Let's continue this journey together!

Home php codes Decode JSON format using php function

Decode JSON format using php function

0

Welcome back to shortlearner.com . Today we will see
how to fetch record from json using php function

Before start this tutorial first of all we should know about JSON.
Basically JSON is Java Script object Notation which is used to transmit data between a server and browser. Below is a basic example of json.

read json format in php

we have two files here, in the first file we have json code and in another one we are fetching all records of json file using some php functions.

data.json

Decode JSON format using php function

[
	{
		"name": "Shefali",
		"race": "Human"
	},
	{
		"name": "Swapnil",
		"race": "Elf"
	},
	{
		"name": "Ankit",
		"race": "Dwarf"
	}
]

Now, we have to create index.php file in which first we will declare path of our json file in a variable $url, and by using file_get_contents function put all the json content of the file into $data variable.
By using json_decode function we deocode the json code and store it into $characters variable. After that by usingforeach loop fetch all data .

Index.php

<?php

$url = 'data.json'; // path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable

$characters = json_decode($data); // decode the JSON feed

echo $characters[0]->name;

foreach ($characters as $character) 
{
  echo $character->name . '<br>';
}

?>

If you have any doubt pleaseĀ  reach to us.