Pulling certain information from Json - php

I've recently been exploring the Xbox API over at XboxAPI.com to try and increase my knowledge and confidence of actually using API's and also using Json Data. I found some code on another question that I had a play around with and got it to give me something back, the code I am currently using is:
$url = 'https://xboxapi.com/v2/2745051201447500/presence';
$headers = array(
'X-AUTH: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
Visiting the page in the browser gives me the following:
{"xuid":2745051201447500,"state":"Online","devices":[{"type":"XboxOne","titles":[{"id":714681658,"name":"Home","placement":"Background","state":"Active","lastModified":"2014-10-07T22:02:34.821235Z"},{"id":446059611,"activity":{"richPresence":"In a Street Race."},"name":"Forza Horizon 2","placement":"Full","state":"Active","lastModified":"2014-10-07T22:02:34.821235Z"}]}]}
My question is, how do I pull certain bits of information out of the above? For example if I wanted to pull the "name" and just display that, how would I go about doing that? I've tried a couple of things including the following:
echo $result->devices[0]->type;
but that didn't work. I don't know how far off I am from the correct answer, but would appreciate any assistance.
Thanks

I suspect you will need some akin to json_decode (http://php.net/manual/en/function.json-decode.php)
:
$result = json_decode(curl_exec($ch);
echo $result->devices->titles->name;
Note: The above has not been tested.

First, do a json_decode like below which will put into an associate array.
Then, you would need also to make sure you use an index on those that are multidimensional as noted below.
And voilla - basically, you're missing the json_decode.
$result = json_decode(curl_exec($ch));
$result->devices[0]->type;
Ugh - also forgot
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
You're curl is not outputting to a string variable.

devices is an array (note the [] in the JSON), so you need
$result->devices[0]->type // XboxOne
^^^
The same will hold for titles - that's also an array and would need [] dereferencing in PHP. a var_dump($result) would show you a nicely formatted structured dump of the array, and show you you exactly what "path" you need to use to get any to any piece of data in it.

Related

JSON string returned from test site includes extra characters preventing json_decode from working

I'm trying to learn about transferring data between servers. There is a test API on line containing json data. I tried the following:-
<?php
// Initiate curl session in a variable (resource) $curl_handle = curl_init();
$url = "http://dummy.restapiexample.com/api/v1/employees"; // website sample API data
// Set the curl URL option curl_setopt($curl_handle, CURLOPT_URL, $url);
// This option will return data as a string instead of direct output curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
// Execute curl & store data in a variable $curl_data = curl_exec($curl_handle);
curl_close($curl_handle);
// Write the JSON string
// echo $curl_data; // the above writes the JSON string ok
// Now try decoding to PHP array
$character = json_decode($curl_data);
echo $character[1]->employee_name;
// this throws an error 'Error: Cannot use object of type stdClass as array in C:\wamp64\www\curlex\curlget.php on line 24'
?>
The string returned has the following content (stripped down to 2 entries for clarity):-
{"status":"success","data":[{"id":"1","employee_name":"Tiger Nixon","employee_salary":"320800","employee_age":"61","profile_image":""},{"id":"2","employee_name":"Garrett Winters","employee_salary":"170750","employee_age":"63","profile_image":""}]}
I imagine json_decode fails because of the {"status":"success","data":preamble? How can this be resolved please?
Your problem is, that you have ommited the second parameter from json_decode() function, which if not set, will parse the string to an object, instead of an array.
You can find the documentation for this function here, what you are looking for it in your case, is the assoc parameter.
On the other hand, the example you show returns the sought employee_name inside another property, and not in the main property (namely data).
Try providing true as the second parameter to the function:
$character = json_decode($curl_data, true);
echo $character[1]['employee_name'];
But this will only work, if the example of the data is not accurate. If that example is accurate, to get the employee_name of the second data element, use:
$character = json_decode($curl_data, true);
echo $character['data'][1]['employee_name'];
Note, that php arrays are zero based, so if you want to get the first element out of an array, you should refer to it's 0th property.
You can access it like this:
$character = json_decode($curl_data);
echo $character->data[1]->employee_name;
Thanks to all who offered help. I hadn't realised that the returned string resulted in a two-dimensional array. I was misled by the web site which gave me the link to the freely available test data.

PHP CURL GET JSON VALUE [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 5 years ago.
Hi I have used curl to get some json api data and that is all working fine. I have ran into a problem when trying to get a specific value. I have decoded the json into an array but I still cant seem to get a specific value.
Here is my code:
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, 'https://bittrex.com/api/v1.1/public/getcurrencies');
$result = curl_exec($curl);
curl_close($curl);
$json = json_decode($result, true);
print_r($json);
so if you go to this url https://bittrex.com/api/v1.1/public/getcurrencies you can see the data I am pulling in. I want to get the value of a Currency.
I tried changing my print to this print_r($json['Currency']); that returned nothing. I also tried this print_r($json[1]); which I thought would at least return something but yet again I got no response.
I have run print_r(gettype($json)); that returned an array so it is 100% an array.
The result of that call is indeed an array, but it's not structured that way. To get the currency of the first result, you'll have to do print_r($json['result'][0]['Currency']), print_r($json['result'][1]['Currency']) for the second result, and so on.
EDIT: Jeff beat me to it.

valid json doesnt work

I am trying to decode a JSON string in PHP,but somehow the json_decode doesnt like my string, i think it is not valid json. The thing that is very strange to me is, that if i put the json response in a variable manually, it is working. If i write the json response out in the browser, and i write the content of the variable, both are completely the same, like this:
{"id":455463,"Created":"2016-04-30T14:20:38.09","SenderCompanyName":"x","InvoiceNumber":"2555","PaymentDueDate":"2016-04-30T00:00:00","ToBePaidAmount":350.0000}
If i look in the webpage source, the content is also completely the same. I have also tryed to convert to UTF8, but no change.
How do you guys usually debug this, or what did i forget ?
code:
// calling web service and saving json response in variable
$json_response = CallAPI($method, $url, $json_request);
// the response contain some unvalid character in the end, so i am removing it
$json_response = substr($json_response, 0, strpos($json_response, "}"));
// trying to decode it, IT PRINTS OUT NULL
var_dump(json_decode($json_response, true));
// copying the json response from the above and putting it into a variable
$json_response = '{"id":455433,"Created":"2016-04-30T12:55:12.313","SenderCompanyName":"x","InvoiceNumber":"2525","PaymentDueDate":"2016-04-30T00:00:00","ToBePaidAmount":350.0000}';
// trying to decode it, IT PRINTS OUT THE RESULT SUCCESFULLY
var_dump(json_decode($json_response, true));
Try this:
<?php
$json = '{"id":455463,"Created":"2016-04-30T14:20:38.09","SenderCompanyName":"x","InvoiceNumber":"2555","PaymentDueDate":"2016-04-30T00:00:00","ToBePaidAmount":350.0000}';
var_dump(json_decode($json));
?>
I finally found the solution.
I had forget to add this in my CURL OPTIONS:
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
After adding this, its working fine

How to display a JSON object with php and cURL?

I'm very new to php (I know next to nothing, in fact) and I'm trying to display an object from a JSON string on a website (probably not the right terminology but you know... I'm new...). Here's the cURL code I'm using:
$url="http://mc.gl:8081/?JSONSERVER=lobby";
// Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
Then I have this that's supposed to do something (I really dont understand it)
// Will dump a beauty json :3
var_dump(json_decode($result));
Annnnnddd.... what do I do next? I've done a lot of googling and nothing seems to work. Here's the string that I should be getting:
{"lobby":{"playeramount":1,"players":{"MisterErwin":"MisterErwin"}},"API-Version":"1","return":true}
and I want to echo "playeramount".
Any help would be greatly appreciated! Thanks so much!
The var_dump() function in PHP is used to display structured information about variables. It is usually used for debugging and has nothing to do with the JSON decode.
In this case, the $result variable will contain the JSON string you need. To decode it, use PHP's built-in function json_decode():
$json = json_decode($result); // decode JSON string into an object
Note: It's also possible to get an associative array by passing TRUE as the second parameter to json_decode().
Once you have the object, you can traverse it to get the required value:
echo $json->lobby->playeramount;
Demo!
If you want to access the result as an associative array, you can do like this too [By passing a true flag in the json_decode() function]
<?php
$str='{"lobby":{"playeramount":1,"players":{"MisterErwin":"MisterErwin"}},"API-Version":"1","return":true}';
$str=json_decode($str,true); // Setting the true flag
echo $str['lobby']['playeramount']; //Outputs 1

PHP Curl: how to pass a variable ? - a beginner question;-)

good evening dear community.
I need a starting-point! A German DB that collects all the data from all German Foundations...
see this url here - just click it to see a search page
<?php
//
// The PHP curl module supports the received page to be returned in a variable
// if told.
//
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.suche.stiftungen.org/index.php?strg=87_124&baseID=129&PHPSESSID=efd25e89a4986cb0981c602fc7c68780");
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$result=curl_exec ($ch);
curl_close ($ch);
?>
Question: Here we find all Foundations in Germany: : 8074 different foundations: You get the full results if you choose % as wildcard in the Search-field. How to do this with PHP: i think that we have to do this with curl or with file_get_contents_ - those are the best methods for doing this: What do you think, personally. I am curious to get your ideas to know! please. lemme know what you think!? BTW - probably - the XPATH and DOM-Technique can be used too. I guess so!?
First approach: see this url here - just click it to see a search page
The way to get through this database is to search (in the search-field) combinations of letters eg "ac" and select search only titles. Then go through every pair of letters. If you still get too many results for a particular pair, use 3 letters. aca, acb,...If i would have a startingpoint i would be happy.
how to enlarge the above written php-code... how to get the variables of my approach into the php-programme...!?
I need to pass the variables as combinations of letters eg "ac" and select search only titles.
Then i have to parse the results - then i have to go through every pair of letters.
look forward to hear from you...
zero
If you want to use % as parameter value in an URL, you need to escape it with urlencode.

Categories