How to get json from cURL with PHP - php

I'm trying to decode a json obtening by cURL with php like this :
$url = 'https://www.toto.com/api/v1/ads/?apikey=titi&code_postal='.$code_postal.'&type_de_bois='.$type_bois;
$cURL = curl_init();
curl_setopt($cURL, CURLOPT_URL, $url);
curl_setopt($cURL, CURLOPT_HTTPGET, true);
curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json'
));
$result = curl_exec($cURL);
curl_close($cURL);
var_dump(json_decode($result, true));
echo json_decode($result);
That returns me that, something which seems to be json :
[{"id":"6918","nom":"X","code_postal":"88120","ville":"town","description":"test","logo":"test.png","url":"test","telephone":true},
[{"id":"6919","nom":"Y","code_postal":"88121","ville":"town1","description":"test","logo":"test.png","url":"test","telephone":true},
[{"id":"6920","nom":"Z","code_postal":"88122","ville":"town2","description":"test","logo":"test.png","url":"test","telephone":true}]
int(1) 1
My question are :
- Why, without echo or print, the array is printed?
- Why json_decode doesn't work propely or why it is only one value ("1")?
Thanks a lot for your answer.

You forgot to use the CURLOPT_RETURNTRANSFER option. So curl_exec() printed the response instead of returning it into $result, and $result just contains the value TRUE that was returned by curl_exec to indicate that it was successful. Add:
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);

It seems like the json data is encoded two times if after using once json_decode(), the result is a json string.
Please check this :
echo json_decode(json_decode($result));
If it won't work, could you provide the response of
echo $result;
to see the server response non parsed by PHP.

Related

curl_exec() automatically runs var_dump()

I've been working on a PHP project using cURL to access external API.
Even though connecting via API is successfully done, one subtle thing bothers me...
That is, "return values of curl_exec($curl) are dumped out automatically".
Here's my codes.
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_HTTPHEADER, ["Content-Type: application/x-www-form-urlencoded"]);
curl_setopt($curl, CURLOPT_URL, 'http://...');
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($some_post_data));
$result = curl_exec($curl);
curl_close($curl);
That's all.
I didn't write "var_dump" or "print_r" or anything to output the result.
Nevertheless, there's always dumped result values on the display... more precisely, the dumping occurs at the line
$result = curl_exec($curl);
Does anyone know what's happening?
Set CURLOPT_RETURNTRANSFER to TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

IBM Watson retuning empty response

I have a simpel php Curl call to get something from curl natural languauge understanding.
This is my code:
$report = strtoupper($report);
$username = 'xxx';
$password = 'xxx';
$url = 'https://gateway.watsonplatform.net/natural-language-understanding /api/v1/analyze?version=2017-02-27&text=Helloethics&features=entities,sentiment,keywords';
// Set post arguments for call
$post_args = array(
'text' => $report
);//Set header arguments for call
$header_args = array(
'Content-Type: text/plain',
'Accept: application/json'
);// Set options for REST call via curl
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_USERPWD, "xxx:xxx");
curl_setopt($curl, CURLOPT_HTTPHEADER, $header_args);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_args);
$status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);print_r($status_code);
// Actual REST call via curl and cleanup (closing) of curl call
$result = curl_exec($curl);
echo "print:";print_r($result);
curl_close($curl);
But it just brings me an empty respons. What do I do wrong? And how can I fix this?
It's possible the extra space in your $url variable is causing problems.
However, if you're sure that's not it, try using var_dump($result) instead of print_r($result).
You're accepting JSON data which initially comes back as a string. I think var_dump() will confirm you need to use $resultArray = json_decode($result, true); before you can use print_r to display your cURL response.
I'd also recommend adding <pre></pre> tags around your output for readability... personal preference though.
If the above solution isn't working, what do you get when you do var_dump($status_code)?
TLDR - always use var_dump() to debug, it can save you on more occasions than you expect.

php curl_exec returns response as 1

I am trying to use curl as below code snippet. I already tried all options i could search for the similar issue. have added all setopt options availabale but still i get response as 1. I am trying post request to server and expecting json response. What am I missing?
$logger->info('url:'.$service_url);
$curl = curl_init();
$curl_post_data = array(
'username' => 'user1',
'password' => 'welcome'
);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS,$curl_post_data);
curl_setopt($curl, CURLOPT_URL, $service_url);
curl_setopt($curl, CURLOPT_HTTPGET, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl,CURLOPT_POST, 1);
curl_setopt($curl,CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl,CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl,CURLOPT_CONNECTTIMEOUT ,3);
curl_setopt($curl,CURLOPT_TIMEOUT, 20);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json'
));
$curl_response = curl_exec($curl);
if ($curl_response === false) {
$info = curl_getinfo($curl);
curl_close($curl);
die('error occured during curl exec. Additioanl info: ' . var_export($info));
}
curl_close($curl);
$logger->info('curl_response 11:'.print_r($curl_response));
$decoded = json_decode($curl_response,JSON_PRETTY_PRINT);
if (isset($decoded->response->status) && $decoded->response->status == 'ERROR') {
die('error occured: ' . $decoded->response->errormessage);
}
$logger->info('response ok!');
$logger->info('decoded:'.print_r($decoded));
Updated for solution:
as suggested just used print_r($curl_response, true) to log the response, and used print_r($decoded['orderId']) to get the specific values.
print_r() prints its output, it doesn't return it. In order to store the output of a call to print_r() in a variable, or send it to a logger or whatnot, you need to pass a truthy value as the second parameter.
$x = print_r($foo); // prints formatted $foo and returns true
$x = print_r($foo, true); // prints nothing and returns formatted $foo
Note: Since you've set CURLOPT_RETURNTRANSFER to true, the call to curl_exec() will already return a string. There's really no need to pass that through print_r(), just dump the string.
Also note: You'll want to verify that json_decode() doesn't return null. And you'll likely also want to verify that the HTTP status code is 200 (which you can do via curl_getinfo().

PHP JSON parsing with cURL

I want to create a simple page that prints the region you are in, I am using an API from this site freegeoip.net. I have it set up so it runs a users ip through the site and returns JSON, however I am having issues parsing that response. This is the code I have written:
<?php
$person = $_SERVER["REMOTE_ADDR"];
$url = "freegeoip.net/json/$person";
$cURL = curl_init();
curl_setopt($cURL, CURLOPT_URL, $url);
curl_setopt($cURL, CURLOPT_HTTPGET, true);
curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json'
));
$result = curl_exec($cURL);
curl_close($cURL);
$json = json_decode($result, true);
echo $json['region_name'];
echo $json['city'];
?>
However for some reason, it still prints the full response from the server API... how do I fix this?
Add the following line after setting CURLOPT_HTTPHEADER:
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, 1);
By default curl_exec() outputs the response out directly and it returns TRUE on success or FALSE on failure. If you set CURLOPT_RETURNTRANSFER to TRUE, curl_exec() will return the actual result of successful operation, but still will return FALSE on failure.

How to parse Curl response?

I am able to send the GET request and receive the response at following line.
$curl_resp = curl_exec($curl);
I used the following to parse the response, but it does not work, I have manually set some values to $curl_resp but still not sure how to access the value of each tag of the xml separately.
$xml = simplexml_load_string($curl_resp);
NOTE: I recevice the actual xml but cant parse it, (I need to get each tag's value separately in a variable)
Code:
<?php
$service_url = ' The Url goes here';
$curl = curl_init($service_url);
$curl_post_data = array(
"PASSWORD" => 'pass',
"USERNAME" => 'username'
);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
$curl_resp = curl_exec($curl);
curl_close($curl);
Your variable $curl_response is different than $curl_resp (what you're trying to parse)
You can access the value of each tag just like any other array.
if the CURLOPT_RETURNTRANSFER option is not set then your $curl_resp will just return true/false.
if it is set you may be returning false or a poorly formed xml string. If you post more code or the actual curl response text we may be able to provide more info.
EDIT:
upon reading the code looks like you are assigning the response text to $curl_response instead of $curl_resp
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, "your url");
curl_setopt($ch, CURLOPT_USERAGENT, 'Googlebot/2.1 (+http://www.google.com/bot.html)');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);

Categories