Extract data from JSON in PHP
Question:
How to extract data from JSON in PHP? Answer:
$jsonString = <<<JSON
{
"name": "John",
"age": "32",
"address": {
"city": "London",
"street": "Laxin street 32",
"zip": "32567"
}
}
JSON;
$user = json_decode($jsonString);
$name = $user->name;
$city = $user->address->city;
Description:
To extract data from a JSON string in PHP first convert it to a JSON object using the json_decode
method. The json_decode()
method takes a JSON encoded string and converts it into a PHP variable.
$data = json_decode($jsonString);
null
is returned if the JSON cannot be decoded or if the encoded data is deeper than the nesting limit.
By default, the json_decode
method returns an stdClass
object. You can get the result as an associative array if sets the second parameter to true:
$dataArray = json_decode($jsonString, true);
So accessing data in JSON object is as simple as:
$city = $user->address->city;
Reference:
json_decode reference
Share "How to extract data from JSON in PHP?"
Related snippets:
- Use PHP ternary operator
- Split a string into words in PHP
- Check if JSON key exists in PHP
- Access object property with hyphen in PHP
- Replace spaces with dashes in PHP
- Replace only the first occurrence of a string in PHP
- Replace last occurrence of a string in a string in PHP
- Extract data from JSON in PHP
- Add minutes to date time in PHP
- Add days to date in PHP
- Get same day in the next week in PHP
- Get time difference in minutes in PHP
- Convert date to timestamp in PHP
- Convert timestamp to DateTime in PHP
- Get the last day of a month from date in PHP
- Remove all attributes from HTML tags in PHP
- Remove HTML tags from a string except p, b, i and br in PHP
- Remove HTML tags from a string in PHP
- Get the number of days between two dates in PHP
- Get yesterday's date in PHP
- Get tomorrow's date in PHP
- Get current time in PHP
- Get actual date in PHP
Tags:
extract, get, access, data, variable, json, php, extract data from json, access JSON data Technical term:
Extract data from JSON in PHP