Can't extract data from Json - php

I can't extract data from json that I got from an api.
I tried for hours, tried all kinds of formats. Read Stackoverflow threads like How do I extract data from JSON with PHP?, but I can't see what I am doing wrong.
This is the code so far:
$api_results = '{"status":"0000","data":{"opening_price":"6998000","closing_price":"7270000","min_price":"6750000","max_price":"7997000","average_price":"7188302.5804","units_traded":"78484.9241002","volume_1day":"78484.9241002","volume_7day":"335611.84181738","buy_price":"7268000","sell_price":"7274000","date":"1510563513031"}}';
$results = json_decode($api_results, true);
// Some variations I tried:
var_dump($results->status[1]);
var_dump($results->data[1]->opening_price);
var_dump($results["data"][1]["opening_price"]);
End result: NULL NULL NULL
What am I doing wrong?
Thanks for the answers! I will upvote the working ones. Seems I got confused in the formating!

<?php
$api_results = '{"status":"0000","data":{"opening_price":"6998000","closing_price":"7270000","min_price":"6750000","max_price":"7997000","average_price":"7188302.5804","units_traded":"78484.9241002","volume_1day":"78484.9241002","volume_7day":"335611.84181738","buy_price":"7268000","sell_price":"7274000","date":"1510563513031"}}';
$results = json_decode($api_results, true);
print_r($results['status']);
echo "</br>";
print_r($results['data']['opening_price']);
Try access your array that way.
The output is :
0000
6998000
Keep an eye for the nested arrays. You need to access their parent array first in order to get their values.

Have you read the documentation of json_decode() (or, at least, the accepted answer of the question you linked)? If you pass TRUE as the second argument to json_decode() (and there is no decent reason to not pass it) then it decodes the JSON to associative arrays and not objects.
The elements in a PHP array can be accessed using the square bracket syntax.
A simple call to print_r($results) tells its structure:
Array
(
[status] => 0000
[data] => Array
(
[opening_price] => 6998000
[closing_price] => 7270000
[min_price] => 6750000
[max_price] => 7997000
[average_price] => 7188302.5804
[units_traded] => 78484.9241002
[volume_1day] => 78484.9241002
[volume_7day] => 335611.84181738
[buy_price] => 7268000
[sell_price] => 7274000
[date] => 1510563513031
)
)
Now, accessing its items is a piece of cake:
echo($results['status']);
# 0000
echo($results['data']['opening_price']);
# 6998000

Remove true from json_decode so you will have object result like Demo
$results = json_decode($api_results);
var_dump($results->status);
var_dump($results->data->opening_price);
When you use json_decode with true the returned objects will be converted into associative arrays.

Use this code like i think work it fine..
<?php
$api_results = '{"status":"0000","data":{"opening_price":"6998000","closing_price":"7270000","min_price":"6750000","max_price":"7997000","average_price":"7188302.5804","units_traded":"78484.9241002","volume_1day":"78484.9241002","volume_7day":"335611.84181738","buy_price":"7268000","sell_price":"7274000","date":"1510563513031"}}';
$results = json_decode($api_results);
print_r($results);
var_dump($results->status);
$var = $results->data;
var_dump($var->opening_price);
?>
stdClass Object
(
[status] => 0000
[data] => stdClass Object
(
[opening_price] => 6998000
[closing_price] => 7270000
[min_price] => 6750000
[max_price] => 7997000
[average_price] => 7188302.5804
[units_traded] => 78484.9241002
[volume_1day] => 78484.9241002
[volume_7day] => 335611.84181738
[buy_price] => 7268000
[sell_price] => 7274000
[date] => 1510563513031
)
)
string(4) "0000"
string(7) "6998000"

Remove true from json_decode and try something like this:
var_dump($results->status);
var_dump($results->data->opening_price);
If you see {} it is refering to objects and [] indicates that it is an array. You're trying to show everything as if they were arrays

You have set the second parameter of json_decode() to true. that means the json will be converted to an array so you are not able to access the data using pointer -> (because it is not an object).
You may access the data like this:
var_dump($results['status'][0]);
var_dump($results['data'][0]['opening_price']);
P.S: Try var_dump($results) to see the exact data, so you know how to access each attribute.

Related

Nested Array Foreach Issue

I am very basic new php learner, i having difficulty to get nested array value, here is my json result:
stdClass Object
(
[title] => Aao Raja - Gabbar Is Back | Chitrangada Singh
[link] => stdClass Object
(
[22] => Array
(
[0] => http://r8---sn-aigllnsk.c.docs.google.com/videoplayback?mime=video%2Fmp4&id=o-AExJcTxRDvCYsfgA1cIvQDs1v-pvLhKjTPdDh67X19vz&dur=145.542&itag=22&pl=48&ip=2a03:b0c0:1:d0::2f6:c001&sparams=dur,expire,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,nh,pl,ratebypass,source,upn&key=cms1&sver=3&expire=1437035009&upn=9lTw9Popb18&ratebypass=yes&source=youtube&lmt=1432539432699196&fexp=901816%2C9407809%2C9408142%2C9408420%2C9408710%2C9409172%2C9412774%2C9412846%2C9413149%2C9415664%2C9415958%2C9416126%2C9416370%2C9416656&ipbits=0&signature=3547894526817B37774A7838F8B68493CDD62101.3F143C74D76E8705800445A4CD4476C4F8BCD988&cms_redirect=yes&mm=31&mn=sn-aigllnsk&ms=au&mt=1437013301&mv=m&nh=IgpwcjAzLmxocjE0KgkxMjcuMC4wLjE&utmg=ytap1
[1] =>
[2] => hd720
)
[43] => Array
(
[0] => http://r8---sn-aigllnsk.c.docs.google.com/videoplayback?mime=video%2Fwebm&id=o-AExJcTxRDvCYsfgA1cIvQDs1v-pvLhKjTPdDh67X19vz&dur=0.000&itag=43&pl=48&ip=2a03:b0c0:1:d0::2f6:c001&sparams=dur,expire,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,nh,pl,ratebypass,source,upn&key=cms1&sver=3&expire=1437035009&upn=9lTw9Popb18&ratebypass=yes&source=youtube&lmt=1428933984759484&fexp=901816%2C9407809%2C9408142%2C9408420%2C9408710%2C9409172%2C9412774%2C9412846%2C9413149%2C9415664%2C9415958%2C9416126%2C9416370%2C9416656&ipbits=0&signature=266C126464ECDB4CC0FF076CD41F07BCC4DA7E34.08D9F13B7BF7D92FD1E1963336CC7FB8F19FE899&cms_redirect=yes&mm=31&mn=sn-aigllnsk&ms=au&mt=1437013301&mv=m&nh=IgpwcjAzLmxocjE0KgkxMjcuMC4wLjE&utmg=ytap1
[1] =>
[2] => medium
)
I can access the Title, but can't access the Link urls:
echo $title = $json->{'title'};
echo $link = $json->{'link'}->{'22'}->{'0'};
How can access the specific link array 22
This echo $title = $json->{'title'}; works because you are accessing an object's property and using -> is the correct way.
In this case $json->{'link'}->{'22'}->{'0'} you are trying to access an array item instead an object's property, because $json->{'link'}->{'22'} is an array and not an object. In this case, you should access it in this way: $json->{'link'}->{'22'}[0]. In order to avoid this kind of issues and, when you decode your JSON to a PHP object, you can pass true as a second parameter to the function json_decode and that will convert the whole object into an array. That way, you don't need to worry about accessing elements as object's attributes, you can access them, always, as array items. So, in this case, it would be: $json["link"]["22"][0].
You're confusing the way you access objects and arrays.
Getting the title is correct via $json->title, but the link should be $json->link->{'22'}[0] - a mixture of objects and arrays.
FYI the {'name'} notation is the same as name - only required when you are including variables in your object name e.g. {$someVar . 'name'}
I suppose you use json_decode() function. Do you know that you can get an array instead of StdClass Object? So, you can use.
<?php
$php_array = json_decode($json_string, true);

Parse Json Object PHP

I want to parse the following Json-Object:
{"multicast_id":123456,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
I was able to succefully parse the values from success, failure, etc, but am having difficulties getting the "error"-msg ("InvalidRegistration").
I access them like this:
$b = json_decode($a, true);
if($b['success'] == 1){
$result = true;
}
How do i access the results / error section?
I tried to do it like this:
$b['results']['error']
but it didn't work.
Thank you for your help, in advance.
After you use json_decode function, a php array will be produced that will have the following structure:
Array
(
[multicast_id] => 123456
[success] => 0
[failure] => 1
[canonical_ids] => 0
[results] => Array
(
[0] => Array
(
[error] => InvalidRegistration
)
)
)
which means that in order to access the error key inside the results array you need to type $b['results'][0]['error']. Of course, this is not the optimal way unless you know that there is always going to be one index in the results array. In the case where an unknown number of indexes existed ([0], [1], [2] ... [n]), it would be a better idea to create a loop and go through each of them.

Access a session value

Here is the Print_r of a $_SESSION variable. I am trying to access the value of user_id.
Array (
[userPieUser] => loggedInUser Object (
[email] => xxxxx#hotmail.com
[hash_pw] => xxxxxxxxx
[user_id] => 3
[clean_username] => scott
[display_username] => scott
[remember_me] => [remember_me_sessid] => c13348e6d296b8d96797eed631b20ad13f58e60af00760620327b019e4773c2d6
)
)
I have tried a dozen or so ways to get that value in PHP, however no luck. such as looping through and doing if ($key = 'user_id'){ echo $value } but that just returns the first element in the array. I'm sure it is rudimentary, however appreciate the help.
The one you're looking for is:
$_SESSION['userPieUser']->user_id
As it is part of the userPieUser object.
You should try:
echo $_SESSION['userPieUser']->user_id;
fyi: There is object withing array 'userPieUser'.
Access the variable like so:
echo $_SESSION['userPieUser']['user_id'];
PHP supports accessing object indicies like this within other object indicies.

JSON decode in PHP from a url

Hello i am new with Json in php. I have a web service that gives me data in json format.
I take this data making decode put when i try to use this data i cant
Here is my code:
$url = "http://www.webinsurer.gr/....;
$json = json_decode(#file_get_contents($url), true);
and if i make debug i see the data i take :
[file] => C:\xampp\htdocs\development.insurancemarket.gr\mvc\protected\models\Ratingsmail.php
[line] => 18
[data] => Array
(
[0] => Array
(
[POL_EXPIREDATE] => 2014-05-19 12:00:00
[INCO_IWCODE] => 41
[INCO_DESC] => MAPFRE ASISTENCIA
[PACK_IWCODE] => 0
[PACK_DESC] =>
[OFFERCODE] =>
[PAYMENTCODE] =>
)
[1] => Array
(.....
But i dont now how to use that data. when i try this :
$b= $json->{1}->{'INCO_IWCODE'};
Debug::debuger($b);
the result is nothing
what is wrong? sorry for long post.
When setting the second argument on json_decode to true, you are actively asking for the data to be returned in an associative array and not objects. Thats why your code didn't work.
Demo
You are converting json to associative array. You need to use;
$b = $json["data"][1]["INCO_IWCODE"];
$a = $json[0]->INCO_IWCODE;
That worked for my guys. thanks you all!!!

working with arrays

I currently do a query which goes through the records and forms an array.
the print_r on query gives me this
print_r($query) yields the following:
Array (
[0] => ( [field1] => COMPLETE [field2] => UNKNOWN [field3] => Test comment )
[1] => ( [field1] => COMPLETE [field2] => UNKNOWN [field3] => comment here )
[2] => ( [field1] => COMPLETE [field2] => UNKNOWN [field3] => checking )
[3] => ( [field1] => COMPLETE [field2] => UNKNOWN [field3] => testing )
[4] => ( [field1] => COMPLETE [field2] => UNKNOWN [field3] => working )
)
somehow I want to take this array and convert it back to php. So for example some thing like this
$myArray = array( ...)
then $myArray should yield the samething as the print_r($query) yeilds.
Thanks
An alternative to serialize that's closer to the print_r output would be
var_export — Outputs or returns a parsable string representation of a variable
var_export() gets structured information about the given variable. It is similar to var_dump() with one exception: the returned representation is valid PHP code.
Note that
var_export() does not handle circular references as it would be close to impossible to generate parsable PHP code for that. If you want to do something with the full representation of an array or object, use serialize().
Using var_export wouldn't allow you to parse back an actual print_r result. But tbh, I find attempting that not very feasible at all. If you have to do that, something is wrong with the code.
I may be underestimating your PHP experience here, but....
You do realize that $query is an array, right? You can simply do $myArray = $query without using print_r() for anything.
Do you need to convert it to text and back? Does it have to be stored somewhere? If so, can you use a different format (serialized or json)?
Use:
$phpcode = "\$myarray = " . var_export($query, true) . ";";
This returns a string representation of your $query array that is valid PHP code.
PS. You're not thinking of using eval() on it later, are you?
$filedata = serialize($query);
// write $filedata to a file
Then in another file:
// some other php file
// read in the filedata
$filedata = file_get_contents("file.dat");
$query = unserialize($filedata);
This is what I assume you meant by converting a string representation of an array into PHP. If you want to actually convert the output of print_r, then you will need to do some serious regex.

Categories