Handling data in a PHP JSON Object
You mean something like this?
<?php
$jsonurl = "http://search.twitter.com/trends.json";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);
foreach ( $json_output->trends as $trend )
{
echo "{$trend->name}\n";
}
How to extract and access data from JSON with 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
Accessing associative array items
When decoding a JSON object to an associative PHP array, you can iterate both keys and values using the foreach (array_expression as $key => $value)
syntax, eg
$json = '
{
"foo": "foo value",
"bar": "bar value",
"baz": "baz value"
}';
$assoc = json_decode($json, true);
foreach ($assoc as $key => $value) {
echo "The value of key '$key' is '$value'", PHP_EOL;
}
Prints
The value of key 'foo' is 'foo value'
The value of key 'bar' is 'bar value'
The value of key 'baz' is 'baz value'
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
)
Take a look at it in this handy interactive JSON explorer.
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.
Access json object values with PHP
You already parse the Json in line 3.
You should be able to go $data[0]->userId
or something
Edit: Notice that $data
is an array of objects so you have to loop through them or specify which one of them you want to access. [] to choose an array element and then -> to access a field on the object
Advanced Json object handling in PHP
You need to use json_decode function if it is json string you are getting in post. Then you can access the object elements.
JSON data handling with mySQL and php
You tagged it as PHP so you can use php functions: json_encode and json_decode.
For example when you read (SELECT) and got this cost value in string corresponding to the primary key 24322:
//after you query db and got the cost in string...
$sql = "SELECT * FROM additional";
$result = mysqli_query($conn,$sql); $row = mysqli_fetch_array($result);
//from your comment below.... just changed to $cost so I don't have to change everything here...
$cost = $row['costs'];
//$cost = '{"telephone" : "$20", "hotel" : "$400"}'
//you just have to:
$cost = json_decode($cost);
// result in an object which you can manipulate such as:
print_r($cost->telephone);
// $20 or:
print_r($cost->hotel);
//$400;
//or if you want to go through all of the costs... you change that to array:
$cost = (array)$cost; //or on your json_decode you add a TRUE param... ie(json_decode($cost, TRUE))...
print_r($cost);
//will produce an associative array: ['telephone'=>'$20', 'hotel'=>'$400']
//for which you can do a foreach if you want to go through each value...
On the other hand when you save to db with an object:
$cost = (object)['hotel'=>'$300', 'taxi'=>'$14'];
//you json_encode this so you can write to db:
$cost = json_encode($cost);
//a string... you can then use $cost to write to db with (insert, update, etc)
Note: json_decode needs the input string to be UTF-8 encoded. So you might need to force your mysql server to provide UTF-8. Some reading: https://www.toptal.com/php/a-utf-8-primer-for-php-and-mysql
Hope this helps...
Using PHP to access JSON objects
You were nearly there - once you use json_decode, it's an object not an array, so you need to use '->' to access its contents like so - https://3v4l.org/ZZNDg
$properties = json_decode($json)->features[0]->properties;
echo($properties->name);
Read JSON Data Using PHP
Use $obj = json_decode($yourJSONString);
to convert it to an object.
Then use foreach($obj->response->docs as $doc)
to iterate over the "docs".
You can then access the fields using $doc->student_id
and $doc->student_name[0]
.
Handling data that is too large for json_encode (PHP)
You need to increase memory limit dynamically:-
ini_set('memory_limit','16M');// change 16M to your desired number
Note:-
The above code will increase the maximum amount of memory available to PHP to 16 MB and this setting is only adjusted for the running script.
Related Topics
PHP: If Internet Explorer 6, 7, 8 , or 9
How to Get Url of Current Page in PHP
Generating Cryptographically Secure Tokens
How to Programmatically Login/Authenticate a User
What Do Strict Types Do in PHP
Mock Private Method With PHPunit
Is There Any Particular Difference Between Intval and Casting to Int - '(Int) X'
Replace Last Occurrence of a String in a String
Which Is Faster in PHP, $Array[] = $Value or Array_Push($Array, $Value)
Convert Utf8-Characters to Iso-88591 and Back in PHP
MySQL Server Has Gone Away - in Exactly 60 Seconds
Best Way to Automatically Remove Comments from PHP Code
Alternative to MySQL_Real_Escape_String Without Connecting to Db
Storing and Displaying Unicode String (हिन्दी) Using PHP and MySQL