How do I extract data from JSON with PHP?
up vote
157
down vote
favorite
This is intended to be a general reference question and answer covering many of the never-ending "How do I access data in my JSON?" questions. It is here to handle the broad basics of decoding JSON in PHP and accessing the results.
I have the JSON:
"type": "donut",
"name": "Cake",
"toppings": [
"id": "5002", "type": "Glazed" ,
"id": "5006", "type": "Chocolate with Sprinkles" ,
"id": "5004", "type": "Maple"
]
How do I decode this in PHP and access the resulting data?
php json
add a comment |
up vote
157
down vote
favorite
This is intended to be a general reference question and answer covering many of the never-ending "How do I access data in my JSON?" questions. It is here to handle the broad basics of decoding JSON in PHP and accessing the results.
I have the JSON:
"type": "donut",
"name": "Cake",
"toppings": [
"id": "5002", "type": "Glazed" ,
"id": "5006", "type": "Chocolate with Sprinkles" ,
"id": "5004", "type": "Maple"
]
How do I decode this in PHP and access the resulting data?
php json
1
Related: Able to see a variable in print_r()'s output, but not sure how to access it in code, interactive JSON exploration in context of PHP is possible here: array.include-once.org
– hakre
Mar 27 '15 at 21:09
Please can I know that why this question not consider as a duplicate question even 9 or less users marked as a duplicate for stackoverflow.com/questions/4343596/parsing-json-file-with-php? M
– I am the Most Stupid Person
Aug 9 '17 at 5:46
@IamtheMostStupidPerson I'll try to explain, even though your username makes me doubt you'll get it ;). This question is asked, and its answers are written, in a "canonical" way. As such, it's a better recipient for duplicate target than the other questions.
– Félix Gagnon-Grenier
Feb 25 at 20:13
add a comment |
up vote
157
down vote
favorite
up vote
157
down vote
favorite
This is intended to be a general reference question and answer covering many of the never-ending "How do I access data in my JSON?" questions. It is here to handle the broad basics of decoding JSON in PHP and accessing the results.
I have the JSON:
"type": "donut",
"name": "Cake",
"toppings": [
"id": "5002", "type": "Glazed" ,
"id": "5006", "type": "Chocolate with Sprinkles" ,
"id": "5004", "type": "Maple"
]
How do I decode this in PHP and access the resulting data?
php json
This is intended to be a general reference question and answer covering many of the never-ending "How do I access data in my JSON?" questions. It is here to handle the broad basics of decoding JSON in PHP and accessing the results.
I have the JSON:
"type": "donut",
"name": "Cake",
"toppings": [
"id": "5002", "type": "Glazed" ,
"id": "5006", "type": "Chocolate with Sprinkles" ,
"id": "5004", "type": "Maple"
]
How do I decode this in PHP and access the resulting data?
php json
php json
edited Sep 28 at 3:33
asked Mar 27 '15 at 19:38
Paul Crovella
16.6k93656
16.6k93656
1
Related: Able to see a variable in print_r()'s output, but not sure how to access it in code, interactive JSON exploration in context of PHP is possible here: array.include-once.org
– hakre
Mar 27 '15 at 21:09
Please can I know that why this question not consider as a duplicate question even 9 or less users marked as a duplicate for stackoverflow.com/questions/4343596/parsing-json-file-with-php? M
– I am the Most Stupid Person
Aug 9 '17 at 5:46
@IamtheMostStupidPerson I'll try to explain, even though your username makes me doubt you'll get it ;). This question is asked, and its answers are written, in a "canonical" way. As such, it's a better recipient for duplicate target than the other questions.
– Félix Gagnon-Grenier
Feb 25 at 20:13
add a comment |
1
Related: Able to see a variable in print_r()'s output, but not sure how to access it in code, interactive JSON exploration in context of PHP is possible here: array.include-once.org
– hakre
Mar 27 '15 at 21:09
Please can I know that why this question not consider as a duplicate question even 9 or less users marked as a duplicate for stackoverflow.com/questions/4343596/parsing-json-file-with-php? M
– I am the Most Stupid Person
Aug 9 '17 at 5:46
@IamtheMostStupidPerson I'll try to explain, even though your username makes me doubt you'll get it ;). This question is asked, and its answers are written, in a "canonical" way. As such, it's a better recipient for duplicate target than the other questions.
– Félix Gagnon-Grenier
Feb 25 at 20:13
1
1
Related: Able to see a variable in print_r()'s output, but not sure how to access it in code, interactive JSON exploration in context of PHP is possible here: array.include-once.org
– hakre
Mar 27 '15 at 21:09
Related: Able to see a variable in print_r()'s output, but not sure how to access it in code, interactive JSON exploration in context of PHP is possible here: array.include-once.org
– hakre
Mar 27 '15 at 21:09
Please can I know that why this question not consider as a duplicate question even 9 or less users marked as a duplicate for stackoverflow.com/questions/4343596/parsing-json-file-with-php? M
– I am the Most Stupid Person
Aug 9 '17 at 5:46
Please can I know that why this question not consider as a duplicate question even 9 or less users marked as a duplicate for stackoverflow.com/questions/4343596/parsing-json-file-with-php? M
– I am the Most Stupid Person
Aug 9 '17 at 5:46
@IamtheMostStupidPerson I'll try to explain, even though your username makes me doubt you'll get it ;). This question is asked, and its answers are written, in a "canonical" way. As such, it's a better recipient for duplicate target than the other questions.
– Félix Gagnon-Grenier
Feb 25 at 20:13
@IamtheMostStupidPerson I'll try to explain, even though your username makes me doubt you'll get it ;). This question is asked, and its answers are written, in a "canonical" way. As such, it's a better recipient for duplicate target than the other questions.
– Félix Gagnon-Grenier
Feb 25 at 20:13
add a comment |
2 Answers
2
active
oldest
votes
up vote
315
down vote
accepted
Intro
First off you have a string. JSON is not an array, an object, or a data structure. JSON is a text-based serialization format - so a fancy string, but still just a string. Decode it in PHP by using json_decode()
.
$data = json_decode($json);
Therein you might find:
- scalars: strings, ints, floats, and bools
nulls (a special type of its own)- compound types: objects and arrays.
These are the things that can be encoded in JSON. Or more accurately, these are PHP's versions of the things that can be encoded in JSON.
There's nothing special about them. They are not "JSON objects" or "JSON arrays." You've decoded the JSON - you now have basic everyday PHP types.
Objects will be instances of stdClass, a built-in class which is just a generic thing that's not important here.
Accessing object properties
You access the properties of one of these objects the same way you would for the public non-static properties of any other object, e.g. $object->property
.
$json = '
"type": "donut",
"name": "Cake"
';
$yummy = json_decode($json);
echo $yummy->type; //donut
Accessing array elements
You access the elements of one of these arrays the same way you would for any other array, e.g. $array[0]
.
$json = '
[
"Glazed",
"Chocolate with Sprinkles",
"Maple"
]';
$toppings = json_decode($json);
echo $toppings[1]; //Chocolate with Sprinkles
Iterate over it with foreach
.
foreach ($toppings as $topping)
echo $topping, "n";
Glazed
Chocolate with Sprinkles
Maple
Or mess about with any of the bazillion built-in array functions.
Accessing nested items
The properties of objects and the elements of arrays might be more objects and/or arrays - you can simply continue to access their properties and members as usual, e.g. $object->array[0]->etc
.
$json = '
"type": "donut",
"name": "Cake",
"toppings": [
"id": "5002", "type": "Glazed" ,
"id": "5006", "type": "Chocolate with Sprinkles" ,
"id": "5004", "type": "Maple"
]
';
$yummy = json_decode($json);
echo $yummy->toppings[2]->id; //5004
Passing true
as the second argument to json_decode()
When you do this, instead of objects you'll get associative arrays - arrays with strings for keys. Again you access the elements thereof as usual, e.g. $array['key']
.
$json = '
"type": "donut",
"name": "Cake",
"toppings": [
"id": "5002", "type": "Glazed" ,
"id": "5006", "type": "Chocolate with Sprinkles" ,
"id": "5004", "type": "Maple"
]
';
$yummy = json_decode($json, true);
echo $yummy['toppings'][2]['type']; //Maple
Don't know how the data is structured
Read the documentation for whatever it is you're getting the JSON from.
Look at the JSON - where you see curly brackets expect an object, where you see square brackets
expect an array.
Hit the decoded data with a print_r()
:
$json = '
"type": "donut",
"name": "Cake",
"toppings": [
"id": "5002", "type": "Glazed" ,
"id": "5006", "type": "Chocolate with Sprinkles" ,
"id": "5004", "type": "Maple"
]
';
$yummy = json_decode($json);
print_r($yummy);
and check the output:
stdClass Object
(
[type] => donut
[name] => Cake
[toppings] => Array
(
[0] => stdClass Object
(
[id] => 5002
[type] => Glazed
)
[1] => stdClass Object
(
[id] => 5006
[type] => Chocolate with Sprinkles
)
[2] => stdClass Object
(
[id] => 5004
[type] => Maple
)
)
)
It'll tell you where you have objects, where you have arrays, along with the names and values of their members.
If you can only get so far into it before you get lost - go that far and hit that with print_r()
:
print_r($yummy->toppings[0]);
stdClass Object
(
[id] => 5002
[type] => Glazed
)
Break the problem down into pieces that are easier to wrap your head around.
json_decode()
returns null
This happens because either:
- The JSON consists entirely of just that,
null
. - The JSON is invalid - check the result of
json_last_error_msg
or put it through something like JSONLint. - It contains elements nested more than 512 levels deep. This default max depth can be overridden by passing an integer as the third argument to
json_decode()
.
If you need to change the max depth you're probably solving the wrong problem. Find out why you're getting such deeply nested data (e.g. the service you're querying that's generating the JSON has a bug) and get that to not happen.
Object property name contains a special character
Sometimes you'll have an object property name that contains something like a hyphen -
or at sign @
which can't be used in a literal identifier. Instead you can use a string literal within curly braces to address it.
$json = '"@attributes":"answer":42';
$thing = json_decode($json);
echo $thing->'@attributes'->answer; //42
If you have an integer as property see: How to access object properties with names like integers? as reference.
Someone put JSON in your JSON
It's ridiculous but it happens - there's JSON encoded as a string within your JSON. Decode, access the string as usual, decode that, and eventually get to what you need.
$json = '
"type": "donut",
"name": "Cake",
"toppings": "[ "type": "Glazed" , "type": "Maple" ]"
';
$yummy = json_decode($json);
$toppings = json_decode($yummy->toppings);
echo $toppings[0]->type; //Glazed
Data doesn't fit in memory
If your JSON is too large for json_decode()
to handle at once things start to get tricky. See:
- Processing large JSON files in PHP
- How to properly iterate through a big json file
How to sort it
See: Reference: all basic ways to sort arrays and data in PHP.
just stumbled at this answer and found that the link to array.include-once.org is broken.
– Jeff
Sep 22 '17 at 22:47
@Jeff Thanks. Shame about that. I've removed the link.
– Paul Crovella
Sep 22 '17 at 23:00
yeah, considering the name of the link and how you've described it, it sounds like a real bummer.
– Jeff
Sep 22 '17 at 23:04
1
Very good explanation. Taught me may things
– GeekWithGlasses
Sep 29 '17 at 13:43
2
Yo Dawg, heard you like JSON so we put JSON in your JSON...
– AbraCadaver
Apr 4 at 20:11
|
show 1 more comment
up vote
8
down vote
You can use json_decode() to convert a json string to a PHP object/array.
Eg.
Input:
$json = '"a":1,"b":2,"c":3,"d":4,"e":5';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
Output:
object(stdClass)#1 (5)
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
array(5)
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
Few Points to remember:
json_decode
requires the string to be a validjson
else it will returnNULL
.- In the event of a failure to decode,
json_last_error()
can be used to determine the exact nature of the error. - Make sure you pass in
utf8
content, orjson_decode
may error out and just return aNULL
value.
2
Why there are downvotes to this answer?!
– candlejack
Dec 28 '16 at 21:39
well, they might not have liked its simplicity, nonetheless. You can always upvote ;)
– Mohd Abdul Mujib
Dec 29 '16 at 3:33
Probably the more likely reason is that it has already been answered and it looks like @MohdAbdulMujib is after some free rep
– Isaac
Jan 11 '17 at 21:18
2
@Isaac some people may not be very keen in reading the whole manual when they just want to begin with using the function. Otherwise they'd be better off reading the official doc. The whole point of SO is the simplicity in which the answers are provided. IMHO
– Mohd Abdul Mujib
Jan 12 '17 at 2:28
add a comment |
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
315
down vote
accepted
Intro
First off you have a string. JSON is not an array, an object, or a data structure. JSON is a text-based serialization format - so a fancy string, but still just a string. Decode it in PHP by using json_decode()
.
$data = json_decode($json);
Therein you might find:
- scalars: strings, ints, floats, and bools
nulls (a special type of its own)- compound types: objects and arrays.
These are the things that can be encoded in JSON. Or more accurately, these are PHP's versions of the things that can be encoded in JSON.
There's nothing special about them. They are not "JSON objects" or "JSON arrays." You've decoded the JSON - you now have basic everyday PHP types.
Objects will be instances of stdClass, a built-in class which is just a generic thing that's not important here.
Accessing object properties
You access the properties of one of these objects the same way you would for the public non-static properties of any other object, e.g. $object->property
.
$json = '
"type": "donut",
"name": "Cake"
';
$yummy = json_decode($json);
echo $yummy->type; //donut
Accessing array elements
You access the elements of one of these arrays the same way you would for any other array, e.g. $array[0]
.
$json = '
[
"Glazed",
"Chocolate with Sprinkles",
"Maple"
]';
$toppings = json_decode($json);
echo $toppings[1]; //Chocolate with Sprinkles
Iterate over it with foreach
.
foreach ($toppings as $topping)
echo $topping, "n";
Glazed
Chocolate with Sprinkles
Maple
Or mess about with any of the bazillion built-in array functions.
Accessing nested items
The properties of objects and the elements of arrays might be more objects and/or arrays - you can simply continue to access their properties and members as usual, e.g. $object->array[0]->etc
.
$json = '
"type": "donut",
"name": "Cake",
"toppings": [
"id": "5002", "type": "Glazed" ,
"id": "5006", "type": "Chocolate with Sprinkles" ,
"id": "5004", "type": "Maple"
]
';
$yummy = json_decode($json);
echo $yummy->toppings[2]->id; //5004
Passing true
as the second argument to json_decode()
When you do this, instead of objects you'll get associative arrays - arrays with strings for keys. Again you access the elements thereof as usual, e.g. $array['key']
.
$json = '
"type": "donut",
"name": "Cake",
"toppings": [
"id": "5002", "type": "Glazed" ,
"id": "5006", "type": "Chocolate with Sprinkles" ,
"id": "5004", "type": "Maple"
]
';
$yummy = json_decode($json, true);
echo $yummy['toppings'][2]['type']; //Maple
Don't know how the data is structured
Read the documentation for whatever it is you're getting the JSON from.
Look at the JSON - where you see curly brackets expect an object, where you see square brackets
expect an array.
Hit the decoded data with a print_r()
:
$json = '
"type": "donut",
"name": "Cake",
"toppings": [
"id": "5002", "type": "Glazed" ,
"id": "5006", "type": "Chocolate with Sprinkles" ,
"id": "5004", "type": "Maple"
]
';
$yummy = json_decode($json);
print_r($yummy);
and check the output:
stdClass Object
(
[type] => donut
[name] => Cake
[toppings] => Array
(
[0] => stdClass Object
(
[id] => 5002
[type] => Glazed
)
[1] => stdClass Object
(
[id] => 5006
[type] => Chocolate with Sprinkles
)
[2] => stdClass Object
(
[id] => 5004
[type] => Maple
)
)
)
It'll tell you where you have objects, where you have arrays, along with the names and values of their members.
If you can only get so far into it before you get lost - go that far and hit that with print_r()
:
print_r($yummy->toppings[0]);
stdClass Object
(
[id] => 5002
[type] => Glazed
)
Break the problem down into pieces that are easier to wrap your head around.
json_decode()
returns null
This happens because either:
- The JSON consists entirely of just that,
null
. - The JSON is invalid - check the result of
json_last_error_msg
or put it through something like JSONLint. - It contains elements nested more than 512 levels deep. This default max depth can be overridden by passing an integer as the third argument to
json_decode()
.
If you need to change the max depth you're probably solving the wrong problem. Find out why you're getting such deeply nested data (e.g. the service you're querying that's generating the JSON has a bug) and get that to not happen.
Object property name contains a special character
Sometimes you'll have an object property name that contains something like a hyphen -
or at sign @
which can't be used in a literal identifier. Instead you can use a string literal within curly braces to address it.
$json = '"@attributes":"answer":42';
$thing = json_decode($json);
echo $thing->'@attributes'->answer; //42
If you have an integer as property see: How to access object properties with names like integers? as reference.
Someone put JSON in your JSON
It's ridiculous but it happens - there's JSON encoded as a string within your JSON. Decode, access the string as usual, decode that, and eventually get to what you need.
$json = '
"type": "donut",
"name": "Cake",
"toppings": "[ "type": "Glazed" , "type": "Maple" ]"
';
$yummy = json_decode($json);
$toppings = json_decode($yummy->toppings);
echo $toppings[0]->type; //Glazed
Data doesn't fit in memory
If your JSON is too large for json_decode()
to handle at once things start to get tricky. See:
- Processing large JSON files in PHP
- How to properly iterate through a big json file
How to sort it
See: Reference: all basic ways to sort arrays and data in PHP.
just stumbled at this answer and found that the link to array.include-once.org is broken.
– Jeff
Sep 22 '17 at 22:47
@Jeff Thanks. Shame about that. I've removed the link.
– Paul Crovella
Sep 22 '17 at 23:00
yeah, considering the name of the link and how you've described it, it sounds like a real bummer.
– Jeff
Sep 22 '17 at 23:04
1
Very good explanation. Taught me may things
– GeekWithGlasses
Sep 29 '17 at 13:43
2
Yo Dawg, heard you like JSON so we put JSON in your JSON...
– AbraCadaver
Apr 4 at 20:11
|
show 1 more comment
up vote
315
down vote
accepted
Intro
First off you have a string. JSON is not an array, an object, or a data structure. JSON is a text-based serialization format - so a fancy string, but still just a string. Decode it in PHP by using json_decode()
.
$data = json_decode($json);
Therein you might find:
- scalars: strings, ints, floats, and bools
nulls (a special type of its own)- compound types: objects and arrays.
These are the things that can be encoded in JSON. Or more accurately, these are PHP's versions of the things that can be encoded in JSON.
There's nothing special about them. They are not "JSON objects" or "JSON arrays." You've decoded the JSON - you now have basic everyday PHP types.
Objects will be instances of stdClass, a built-in class which is just a generic thing that's not important here.
Accessing object properties
You access the properties of one of these objects the same way you would for the public non-static properties of any other object, e.g. $object->property
.
$json = '
"type": "donut",
"name": "Cake"
';
$yummy = json_decode($json);
echo $yummy->type; //donut
Accessing array elements
You access the elements of one of these arrays the same way you would for any other array, e.g. $array[0]
.
$json = '
[
"Glazed",
"Chocolate with Sprinkles",
"Maple"
]';
$toppings = json_decode($json);
echo $toppings[1]; //Chocolate with Sprinkles
Iterate over it with foreach
.
foreach ($toppings as $topping)
echo $topping, "n";
Glazed
Chocolate with Sprinkles
Maple
Or mess about with any of the bazillion built-in array functions.
Accessing nested items
The properties of objects and the elements of arrays might be more objects and/or arrays - you can simply continue to access their properties and members as usual, e.g. $object->array[0]->etc
.
$json = '
"type": "donut",
"name": "Cake",
"toppings": [
"id": "5002", "type": "Glazed" ,
"id": "5006", "type": "Chocolate with Sprinkles" ,
"id": "5004", "type": "Maple"
]
';
$yummy = json_decode($json);
echo $yummy->toppings[2]->id; //5004
Passing true
as the second argument to json_decode()
When you do this, instead of objects you'll get associative arrays - arrays with strings for keys. Again you access the elements thereof as usual, e.g. $array['key']
.
$json = '
"type": "donut",
"name": "Cake",
"toppings": [
"id": "5002", "type": "Glazed" ,
"id": "5006", "type": "Chocolate with Sprinkles" ,
"id": "5004", "type": "Maple"
]
';
$yummy = json_decode($json, true);
echo $yummy['toppings'][2]['type']; //Maple
Don't know how the data is structured
Read the documentation for whatever it is you're getting the JSON from.
Look at the JSON - where you see curly brackets expect an object, where you see square brackets
expect an array.
Hit the decoded data with a print_r()
:
$json = '
"type": "donut",
"name": "Cake",
"toppings": [
"id": "5002", "type": "Glazed" ,
"id": "5006", "type": "Chocolate with Sprinkles" ,
"id": "5004", "type": "Maple"
]
';
$yummy = json_decode($json);
print_r($yummy);
and check the output:
stdClass Object
(
[type] => donut
[name] => Cake
[toppings] => Array
(
[0] => stdClass Object
(
[id] => 5002
[type] => Glazed
)
[1] => stdClass Object
(
[id] => 5006
[type] => Chocolate with Sprinkles
)
[2] => stdClass Object
(
[id] => 5004
[type] => Maple
)
)
)
It'll tell you where you have objects, where you have arrays, along with the names and values of their members.
If you can only get so far into it before you get lost - go that far and hit that with print_r()
:
print_r($yummy->toppings[0]);
stdClass Object
(
[id] => 5002
[type] => Glazed
)
Break the problem down into pieces that are easier to wrap your head around.
json_decode()
returns null
This happens because either:
- The JSON consists entirely of just that,
null
. - The JSON is invalid - check the result of
json_last_error_msg
or put it through something like JSONLint. - It contains elements nested more than 512 levels deep. This default max depth can be overridden by passing an integer as the third argument to
json_decode()
.
If you need to change the max depth you're probably solving the wrong problem. Find out why you're getting such deeply nested data (e.g. the service you're querying that's generating the JSON has a bug) and get that to not happen.
Object property name contains a special character
Sometimes you'll have an object property name that contains something like a hyphen -
or at sign @
which can't be used in a literal identifier. Instead you can use a string literal within curly braces to address it.
$json = '"@attributes":"answer":42';
$thing = json_decode($json);
echo $thing->'@attributes'->answer; //42
If you have an integer as property see: How to access object properties with names like integers? as reference.
Someone put JSON in your JSON
It's ridiculous but it happens - there's JSON encoded as a string within your JSON. Decode, access the string as usual, decode that, and eventually get to what you need.
$json = '
"type": "donut",
"name": "Cake",
"toppings": "[ "type": "Glazed" , "type": "Maple" ]"
';
$yummy = json_decode($json);
$toppings = json_decode($yummy->toppings);
echo $toppings[0]->type; //Glazed
Data doesn't fit in memory
If your JSON is too large for json_decode()
to handle at once things start to get tricky. See:
- Processing large JSON files in PHP
- How to properly iterate through a big json file
How to sort it
See: Reference: all basic ways to sort arrays and data in PHP.
just stumbled at this answer and found that the link to array.include-once.org is broken.
– Jeff
Sep 22 '17 at 22:47
@Jeff Thanks. Shame about that. I've removed the link.
– Paul Crovella
Sep 22 '17 at 23:00
yeah, considering the name of the link and how you've described it, it sounds like a real bummer.
– Jeff
Sep 22 '17 at 23:04
1
Very good explanation. Taught me may things
– GeekWithGlasses
Sep 29 '17 at 13:43
2
Yo Dawg, heard you like JSON so we put JSON in your JSON...
– AbraCadaver
Apr 4 at 20:11
|
show 1 more comment
up vote
315
down vote
accepted
up vote
315
down vote
accepted
Intro
First off you have a string. JSON is not an array, an object, or a data structure. JSON is a text-based serialization format - so a fancy string, but still just a string. Decode it in PHP by using json_decode()
.
$data = json_decode($json);
Therein you might find:
- scalars: strings, ints, floats, and bools
nulls (a special type of its own)- compound types: objects and arrays.
These are the things that can be encoded in JSON. Or more accurately, these are PHP's versions of the things that can be encoded in JSON.
There's nothing special about them. They are not "JSON objects" or "JSON arrays." You've decoded the JSON - you now have basic everyday PHP types.
Objects will be instances of stdClass, a built-in class which is just a generic thing that's not important here.
Accessing object properties
You access the properties of one of these objects the same way you would for the public non-static properties of any other object, e.g. $object->property
.
$json = '
"type": "donut",
"name": "Cake"
';
$yummy = json_decode($json);
echo $yummy->type; //donut
Accessing array elements
You access the elements of one of these arrays the same way you would for any other array, e.g. $array[0]
.
$json = '
[
"Glazed",
"Chocolate with Sprinkles",
"Maple"
]';
$toppings = json_decode($json);
echo $toppings[1]; //Chocolate with Sprinkles
Iterate over it with foreach
.
foreach ($toppings as $topping)
echo $topping, "n";
Glazed
Chocolate with Sprinkles
Maple
Or mess about with any of the bazillion built-in array functions.
Accessing nested items
The properties of objects and the elements of arrays might be more objects and/or arrays - you can simply continue to access their properties and members as usual, e.g. $object->array[0]->etc
.
$json = '
"type": "donut",
"name": "Cake",
"toppings": [
"id": "5002", "type": "Glazed" ,
"id": "5006", "type": "Chocolate with Sprinkles" ,
"id": "5004", "type": "Maple"
]
';
$yummy = json_decode($json);
echo $yummy->toppings[2]->id; //5004
Passing true
as the second argument to json_decode()
When you do this, instead of objects you'll get associative arrays - arrays with strings for keys. Again you access the elements thereof as usual, e.g. $array['key']
.
$json = '
"type": "donut",
"name": "Cake",
"toppings": [
"id": "5002", "type": "Glazed" ,
"id": "5006", "type": "Chocolate with Sprinkles" ,
"id": "5004", "type": "Maple"
]
';
$yummy = json_decode($json, true);
echo $yummy['toppings'][2]['type']; //Maple
Don't know how the data is structured
Read the documentation for whatever it is you're getting the JSON from.
Look at the JSON - where you see curly brackets expect an object, where you see square brackets
expect an array.
Hit the decoded data with a print_r()
:
$json = '
"type": "donut",
"name": "Cake",
"toppings": [
"id": "5002", "type": "Glazed" ,
"id": "5006", "type": "Chocolate with Sprinkles" ,
"id": "5004", "type": "Maple"
]
';
$yummy = json_decode($json);
print_r($yummy);
and check the output:
stdClass Object
(
[type] => donut
[name] => Cake
[toppings] => Array
(
[0] => stdClass Object
(
[id] => 5002
[type] => Glazed
)
[1] => stdClass Object
(
[id] => 5006
[type] => Chocolate with Sprinkles
)
[2] => stdClass Object
(
[id] => 5004
[type] => Maple
)
)
)
It'll tell you where you have objects, where you have arrays, along with the names and values of their members.
If you can only get so far into it before you get lost - go that far and hit that with print_r()
:
print_r($yummy->toppings[0]);
stdClass Object
(
[id] => 5002
[type] => Glazed
)
Break the problem down into pieces that are easier to wrap your head around.
json_decode()
returns null
This happens because either:
- The JSON consists entirely of just that,
null
. - The JSON is invalid - check the result of
json_last_error_msg
or put it through something like JSONLint. - It contains elements nested more than 512 levels deep. This default max depth can be overridden by passing an integer as the third argument to
json_decode()
.
If you need to change the max depth you're probably solving the wrong problem. Find out why you're getting such deeply nested data (e.g. the service you're querying that's generating the JSON has a bug) and get that to not happen.
Object property name contains a special character
Sometimes you'll have an object property name that contains something like a hyphen -
or at sign @
which can't be used in a literal identifier. Instead you can use a string literal within curly braces to address it.
$json = '"@attributes":"answer":42';
$thing = json_decode($json);
echo $thing->'@attributes'->answer; //42
If you have an integer as property see: How to access object properties with names like integers? as reference.
Someone put JSON in your JSON
It's ridiculous but it happens - there's JSON encoded as a string within your JSON. Decode, access the string as usual, decode that, and eventually get to what you need.
$json = '
"type": "donut",
"name": "Cake",
"toppings": "[ "type": "Glazed" , "type": "Maple" ]"
';
$yummy = json_decode($json);
$toppings = json_decode($yummy->toppings);
echo $toppings[0]->type; //Glazed
Data doesn't fit in memory
If your JSON is too large for json_decode()
to handle at once things start to get tricky. See:
- Processing large JSON files in PHP
- How to properly iterate through a big json file
How to sort it
See: Reference: all basic ways to sort arrays and data in PHP.
Intro
First off you have a string. JSON is not an array, an object, or a data structure. JSON is a text-based serialization format - so a fancy string, but still just a string. Decode it in PHP by using json_decode()
.
$data = json_decode($json);
Therein you might find:
- scalars: strings, ints, floats, and bools
nulls (a special type of its own)- compound types: objects and arrays.
These are the things that can be encoded in JSON. Or more accurately, these are PHP's versions of the things that can be encoded in JSON.
There's nothing special about them. They are not "JSON objects" or "JSON arrays." You've decoded the JSON - you now have basic everyday PHP types.
Objects will be instances of stdClass, a built-in class which is just a generic thing that's not important here.
Accessing object properties
You access the properties of one of these objects the same way you would for the public non-static properties of any other object, e.g. $object->property
.
$json = '
"type": "donut",
"name": "Cake"
';
$yummy = json_decode($json);
echo $yummy->type; //donut
Accessing array elements
You access the elements of one of these arrays the same way you would for any other array, e.g. $array[0]
.
$json = '
[
"Glazed",
"Chocolate with Sprinkles",
"Maple"
]';
$toppings = json_decode($json);
echo $toppings[1]; //Chocolate with Sprinkles
Iterate over it with foreach
.
foreach ($toppings as $topping)
echo $topping, "n";
Glazed
Chocolate with Sprinkles
Maple
Or mess about with any of the bazillion built-in array functions.
Accessing nested items
The properties of objects and the elements of arrays might be more objects and/or arrays - you can simply continue to access their properties and members as usual, e.g. $object->array[0]->etc
.
$json = '
"type": "donut",
"name": "Cake",
"toppings": [
"id": "5002", "type": "Glazed" ,
"id": "5006", "type": "Chocolate with Sprinkles" ,
"id": "5004", "type": "Maple"
]
';
$yummy = json_decode($json);
echo $yummy->toppings[2]->id; //5004
Passing true
as the second argument to json_decode()
When you do this, instead of objects you'll get associative arrays - arrays with strings for keys. Again you access the elements thereof as usual, e.g. $array['key']
.
$json = '
"type": "donut",
"name": "Cake",
"toppings": [
"id": "5002", "type": "Glazed" ,
"id": "5006", "type": "Chocolate with Sprinkles" ,
"id": "5004", "type": "Maple"
]
';
$yummy = json_decode($json, true);
echo $yummy['toppings'][2]['type']; //Maple
Don't know how the data is structured
Read the documentation for whatever it is you're getting the JSON from.
Look at the JSON - where you see curly brackets expect an object, where you see square brackets
expect an array.
Hit the decoded data with a print_r()
:
$json = '
"type": "donut",
"name": "Cake",
"toppings": [
"id": "5002", "type": "Glazed" ,
"id": "5006", "type": "Chocolate with Sprinkles" ,
"id": "5004", "type": "Maple"
]
';
$yummy = json_decode($json);
print_r($yummy);
and check the output:
stdClass Object
(
[type] => donut
[name] => Cake
[toppings] => Array
(
[0] => stdClass Object
(
[id] => 5002
[type] => Glazed
)
[1] => stdClass Object
(
[id] => 5006
[type] => Chocolate with Sprinkles
)
[2] => stdClass Object
(
[id] => 5004
[type] => Maple
)
)
)
It'll tell you where you have objects, where you have arrays, along with the names and values of their members.
If you can only get so far into it before you get lost - go that far and hit that with print_r()
:
print_r($yummy->toppings[0]);
stdClass Object
(
[id] => 5002
[type] => Glazed
)
Break the problem down into pieces that are easier to wrap your head around.
json_decode()
returns null
This happens because either:
- The JSON consists entirely of just that,
null
. - The JSON is invalid - check the result of
json_last_error_msg
or put it through something like JSONLint. - It contains elements nested more than 512 levels deep. This default max depth can be overridden by passing an integer as the third argument to
json_decode()
.
If you need to change the max depth you're probably solving the wrong problem. Find out why you're getting such deeply nested data (e.g. the service you're querying that's generating the JSON has a bug) and get that to not happen.
Object property name contains a special character
Sometimes you'll have an object property name that contains something like a hyphen -
or at sign @
which can't be used in a literal identifier. Instead you can use a string literal within curly braces to address it.
$json = '"@attributes":"answer":42';
$thing = json_decode($json);
echo $thing->'@attributes'->answer; //42
If you have an integer as property see: How to access object properties with names like integers? as reference.
Someone put JSON in your JSON
It's ridiculous but it happens - there's JSON encoded as a string within your JSON. Decode, access the string as usual, decode that, and eventually get to what you need.
$json = '
"type": "donut",
"name": "Cake",
"toppings": "[ "type": "Glazed" , "type": "Maple" ]"
';
$yummy = json_decode($json);
$toppings = json_decode($yummy->toppings);
echo $toppings[0]->type; //Glazed
Data doesn't fit in memory
If your JSON is too large for json_decode()
to handle at once things start to get tricky. See:
- Processing large JSON files in PHP
- How to properly iterate through a big json file
How to sort it
See: Reference: all basic ways to sort arrays and data in PHP.
edited Sep 22 '17 at 23:00
answered Mar 27 '15 at 19:38
Paul Crovella
16.6k93656
16.6k93656
just stumbled at this answer and found that the link to array.include-once.org is broken.
– Jeff
Sep 22 '17 at 22:47
@Jeff Thanks. Shame about that. I've removed the link.
– Paul Crovella
Sep 22 '17 at 23:00
yeah, considering the name of the link and how you've described it, it sounds like a real bummer.
– Jeff
Sep 22 '17 at 23:04
1
Very good explanation. Taught me may things
– GeekWithGlasses
Sep 29 '17 at 13:43
2
Yo Dawg, heard you like JSON so we put JSON in your JSON...
– AbraCadaver
Apr 4 at 20:11
|
show 1 more comment
just stumbled at this answer and found that the link to array.include-once.org is broken.
– Jeff
Sep 22 '17 at 22:47
@Jeff Thanks. Shame about that. I've removed the link.
– Paul Crovella
Sep 22 '17 at 23:00
yeah, considering the name of the link and how you've described it, it sounds like a real bummer.
– Jeff
Sep 22 '17 at 23:04
1
Very good explanation. Taught me may things
– GeekWithGlasses
Sep 29 '17 at 13:43
2
Yo Dawg, heard you like JSON so we put JSON in your JSON...
– AbraCadaver
Apr 4 at 20:11
just stumbled at this answer and found that the link to array.include-once.org is broken.
– Jeff
Sep 22 '17 at 22:47
just stumbled at this answer and found that the link to array.include-once.org is broken.
– Jeff
Sep 22 '17 at 22:47
@Jeff Thanks. Shame about that. I've removed the link.
– Paul Crovella
Sep 22 '17 at 23:00
@Jeff Thanks. Shame about that. I've removed the link.
– Paul Crovella
Sep 22 '17 at 23:00
yeah, considering the name of the link and how you've described it, it sounds like a real bummer.
– Jeff
Sep 22 '17 at 23:04
yeah, considering the name of the link and how you've described it, it sounds like a real bummer.
– Jeff
Sep 22 '17 at 23:04
1
1
Very good explanation. Taught me may things
– GeekWithGlasses
Sep 29 '17 at 13:43
Very good explanation. Taught me may things
– GeekWithGlasses
Sep 29 '17 at 13:43
2
2
Yo Dawg, heard you like JSON so we put JSON in your JSON...
– AbraCadaver
Apr 4 at 20:11
Yo Dawg, heard you like JSON so we put JSON in your JSON...
– AbraCadaver
Apr 4 at 20:11
|
show 1 more comment
up vote
8
down vote
You can use json_decode() to convert a json string to a PHP object/array.
Eg.
Input:
$json = '"a":1,"b":2,"c":3,"d":4,"e":5';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
Output:
object(stdClass)#1 (5)
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
array(5)
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
Few Points to remember:
json_decode
requires the string to be a validjson
else it will returnNULL
.- In the event of a failure to decode,
json_last_error()
can be used to determine the exact nature of the error. - Make sure you pass in
utf8
content, orjson_decode
may error out and just return aNULL
value.
2
Why there are downvotes to this answer?!
– candlejack
Dec 28 '16 at 21:39
well, they might not have liked its simplicity, nonetheless. You can always upvote ;)
– Mohd Abdul Mujib
Dec 29 '16 at 3:33
Probably the more likely reason is that it has already been answered and it looks like @MohdAbdulMujib is after some free rep
– Isaac
Jan 11 '17 at 21:18
2
@Isaac some people may not be very keen in reading the whole manual when they just want to begin with using the function. Otherwise they'd be better off reading the official doc. The whole point of SO is the simplicity in which the answers are provided. IMHO
– Mohd Abdul Mujib
Jan 12 '17 at 2:28
add a comment |
up vote
8
down vote
You can use json_decode() to convert a json string to a PHP object/array.
Eg.
Input:
$json = '"a":1,"b":2,"c":3,"d":4,"e":5';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
Output:
object(stdClass)#1 (5)
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
array(5)
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
Few Points to remember:
json_decode
requires the string to be a validjson
else it will returnNULL
.- In the event of a failure to decode,
json_last_error()
can be used to determine the exact nature of the error. - Make sure you pass in
utf8
content, orjson_decode
may error out and just return aNULL
value.
2
Why there are downvotes to this answer?!
– candlejack
Dec 28 '16 at 21:39
well, they might not have liked its simplicity, nonetheless. You can always upvote ;)
– Mohd Abdul Mujib
Dec 29 '16 at 3:33
Probably the more likely reason is that it has already been answered and it looks like @MohdAbdulMujib is after some free rep
– Isaac
Jan 11 '17 at 21:18
2
@Isaac some people may not be very keen in reading the whole manual when they just want to begin with using the function. Otherwise they'd be better off reading the official doc. The whole point of SO is the simplicity in which the answers are provided. IMHO
– Mohd Abdul Mujib
Jan 12 '17 at 2:28
add a comment |
up vote
8
down vote
up vote
8
down vote
You can use json_decode() to convert a json string to a PHP object/array.
Eg.
Input:
$json = '"a":1,"b":2,"c":3,"d":4,"e":5';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
Output:
object(stdClass)#1 (5)
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
array(5)
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
Few Points to remember:
json_decode
requires the string to be a validjson
else it will returnNULL
.- In the event of a failure to decode,
json_last_error()
can be used to determine the exact nature of the error. - Make sure you pass in
utf8
content, orjson_decode
may error out and just return aNULL
value.
You can use json_decode() to convert a json string to a PHP object/array.
Eg.
Input:
$json = '"a":1,"b":2,"c":3,"d":4,"e":5';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
Output:
object(stdClass)#1 (5)
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
array(5)
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
Few Points to remember:
json_decode
requires the string to be a validjson
else it will returnNULL
.- In the event of a failure to decode,
json_last_error()
can be used to determine the exact nature of the error. - Make sure you pass in
utf8
content, orjson_decode
may error out and just return aNULL
value.
answered Oct 26 '16 at 13:24
Mohd Abdul Mujib
5,96543558
5,96543558
2
Why there are downvotes to this answer?!
– candlejack
Dec 28 '16 at 21:39
well, they might not have liked its simplicity, nonetheless. You can always upvote ;)
– Mohd Abdul Mujib
Dec 29 '16 at 3:33
Probably the more likely reason is that it has already been answered and it looks like @MohdAbdulMujib is after some free rep
– Isaac
Jan 11 '17 at 21:18
2
@Isaac some people may not be very keen in reading the whole manual when they just want to begin with using the function. Otherwise they'd be better off reading the official doc. The whole point of SO is the simplicity in which the answers are provided. IMHO
– Mohd Abdul Mujib
Jan 12 '17 at 2:28
add a comment |
2
Why there are downvotes to this answer?!
– candlejack
Dec 28 '16 at 21:39
well, they might not have liked its simplicity, nonetheless. You can always upvote ;)
– Mohd Abdul Mujib
Dec 29 '16 at 3:33
Probably the more likely reason is that it has already been answered and it looks like @MohdAbdulMujib is after some free rep
– Isaac
Jan 11 '17 at 21:18
2
@Isaac some people may not be very keen in reading the whole manual when they just want to begin with using the function. Otherwise they'd be better off reading the official doc. The whole point of SO is the simplicity in which the answers are provided. IMHO
– Mohd Abdul Mujib
Jan 12 '17 at 2:28
2
2
Why there are downvotes to this answer?!
– candlejack
Dec 28 '16 at 21:39
Why there are downvotes to this answer?!
– candlejack
Dec 28 '16 at 21:39
well, they might not have liked its simplicity, nonetheless. You can always upvote ;)
– Mohd Abdul Mujib
Dec 29 '16 at 3:33
well, they might not have liked its simplicity, nonetheless. You can always upvote ;)
– Mohd Abdul Mujib
Dec 29 '16 at 3:33
Probably the more likely reason is that it has already been answered and it looks like @MohdAbdulMujib is after some free rep
– Isaac
Jan 11 '17 at 21:18
Probably the more likely reason is that it has already been answered and it looks like @MohdAbdulMujib is after some free rep
– Isaac
Jan 11 '17 at 21:18
2
2
@Isaac some people may not be very keen in reading the whole manual when they just want to begin with using the function. Otherwise they'd be better off reading the official doc. The whole point of SO is the simplicity in which the answers are provided. IMHO
– Mohd Abdul Mujib
Jan 12 '17 at 2:28
@Isaac some people may not be very keen in reading the whole manual when they just want to begin with using the function. Otherwise they'd be better off reading the official doc. The whole point of SO is the simplicity in which the answers are provided. IMHO
– Mohd Abdul Mujib
Jan 12 '17 at 2:28
add a comment |
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f29308898%2fhow-do-i-extract-data-from-json-with-php%23new-answer', 'question_page');
);
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
1
Related: Able to see a variable in print_r()'s output, but not sure how to access it in code, interactive JSON exploration in context of PHP is possible here: array.include-once.org
– hakre
Mar 27 '15 at 21:09
Please can I know that why this question not consider as a duplicate question even 9 or less users marked as a duplicate for stackoverflow.com/questions/4343596/parsing-json-file-with-php? M
– I am the Most Stupid Person
Aug 9 '17 at 5:46
@IamtheMostStupidPerson I'll try to explain, even though your username makes me doubt you'll get it ;). This question is asked, and its answers are written, in a "canonical" way. As such, it's a better recipient for duplicate target than the other questions.
– Félix Gagnon-Grenier
Feb 25 at 20:13