getting NULL with cURL but Array with file_get_contents() - php

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.

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

cURL in PHP returns different data in _FILE and _RETURNTRANSFER

I have noticed that cURL in PHP returns different data when told to output to a file via CURLOPT_FILE as it does when told to send the output to a string via CURLOPT_RETURNTRANSFER.
_RETURNTRANSFER seems to strip newlines and extra white space as if parsing it for display as standard HTML code. _FILE on the other hand preserves the file exactly as it was intended.
I have read through the documentation on php.net but haven't found anything that seems to solve my problem. Ideally, I would like to have _RETURNTRANSFER return the exact contents so I could eliminate an intermediate file, but I don't see any way of making this possible.
Here is the code I am using. The data in question is a CSV file with \r\n line endings.
function update_roster() {
$url = "http://example.com/";
$userID = "xx";
$apikey = "xxx";
$passfields = "userID=$userID&apikey=$apikey";
$file = fopen("roster.csv","w+");
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $passfields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, $file);
$variable_in_question = curl_exec ($ch);
curl_close ($ch);
fclose($file);
return $variable_in_question;
}
Turns out, the error is not in what was being returned, but in the way I was going about parsing it. \r\n is not parsed the way I expected when put in single quotes, switching to double quotes solved my problem. I was not aware that this made a difference inside function calls like that.
This works just fine:$cresult = split("\r\n", $cresult);
This does not: $cresult = split('\r\n', $cresult);
Turns out, the error is not in what was being returned, but in the way I was going about parsing it. \r\n is not parsed the way I expected when put in single quotes, switching to double quotes solved my problem. I was not aware that this made a difference inside function calls like that.
This works just fine:$cresult = split("\r\n", $cresult);
This does not: $cresult = split('\r\n', $cresult);
In most scripting langage (it's also true in Bash for instance), simple quotes are used to represent things as they are written, whereas double quotes are "analysed" (i don't think it's the appropriate word but i can't find better).
$str = 'foo';
echo '$str'; // print “$str” to the screen
echo "$str"; // print “foo” to the screen
It is true for variables and escaped characters.
I didn't try to reproduce the "bug" (I think we can consider this as a bug if it is the actual behavior), but maybe you could get over it.
The PHP Doc says that the default comportement is to write the result to a file, and that the default file is STDOUT (the browser's window). What you want is to get the same result than in a file but in a variable.
You could do that using ob_start(); and ob_get_clean();.
$ch = curl_init(...);
// ...
ob_start();
curl_exec($ch);
$yourResult = ob_get_clean();
curl_close($ch);
I know that's not really the clean way (if there is one), but at least it sould work fine.
(Please excuse me if my english is not perfect ;-)...)

Categories