PHP CURL GET JSON VALUE [duplicate] - php

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.

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.

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

Pulling certain information from Json

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.

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

getting NULL with cURL but Array with file_get_contents()

I'm having problem with CURL from a link. I'm able to get an output with file_get_contents(); But having problems with CURL
use json_decode I get a NULL with cURL, but with file_get_contents() I get an Array
Using cURL
$url="https://example.com/"
$ch= curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$json= json_decode(curl_exec($ch),true);
echo $json; //outputs NULL
Using file_get_contents();
$json_pi = file_get_contents($url);
echo json_decode($json_pi,true);
Can anyone help me understand cURL? And why I might be getting these two conflicting results?
Thank you!
You are not doing any error checking after your calls, so if something goes wrong, you will never hear about it.
Check the result of the CURL call using curl_error()
Check the result of the json_encode() call using json_last_error() (PHP >= 5.3)
one of these will probably reveal what the problem is. For example, it could be that the curl call fetches the data in a non-UTF-8 character set, which will cause json_decode() to break - it expects UTF-8 data at all times.

Categories