How to get data from json in php?

Member

by aubrey , in category: PHP General , 5 months ago

How to get data from json in php?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by mallory_cormier , 5 months ago

@aubrey 

To get data from a JSON file in PHP, you can use the json_decode() function to convert the JSON string into a PHP object or an associative array.


Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// JSON string
$jsonString = '{"name":"John", "age":30, "city":"New York"}';

// Convert JSON string to object
$dataObject = json_decode($jsonString);

// Access data using object notation
echo $dataObject->name;  // Output: John

// Convert JSON string to associative array
$dataArray = json_decode($jsonString, true);

// Access data using array notation
echo $dataArray['age'];  // Output: 30


In this example, the JSON string {"name":"John", "age":30, "city":"New York"} is being converted into a PHP object and an associative array using json_decode().


Once it is converted, you can access the data using object notation ($dataObject->name) or array notation ($dataArray['age']).

by herminia_bruen , 5 months ago

@aubrey 

If your JSON data is stored in a file, you can use file_get_contents() to read the file and then use the json_decode() function to convert the JSON string into a PHP object or array.


Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// Read JSON data from a file
$jsonString = file_get_contents('data.json');

// Convert JSON string to object
$dataObject = json_decode($jsonString);

// Access data using object notation
echo $dataObject->name;

// Convert JSON string to associative array
$dataArray = json_decode($jsonString, true);

// Access data using array notation
echo $dataArray['age'];


Make sure to replace 'data.json' with the path to your JSON file.


Note: If you're working with a remote JSON file, you can use functions like file_get_contents() or cURL to fetch the JSON data from the URL.