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.
Related
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);
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.
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().
This question has been asked. But any of those didn't work out for me. I am getting NULL when CURL call is made all the time.
The following is my list_clients.php file.
<?php
require_once 'init.php';
header('Content-Type: application/json');
$clientResults = mysqli_query($link, "SELECT * FROM clients");
$clients = array();
while($client = mysqli_fetch_assoc($clientResults)){
$clients[] = $client;
}
echo json_encode($clients);
exit;
So the output of the above is :
[{"ip_address":"192.168.177.137","mac_address":"3a:1a:cf:7c:92:89","added_on":"2017-08-19 12:48:34"},{"ip_address":"192.168.177.137","mac_address":"3a:1a:cf:7c:92:89","added_on":"2017-08-20 08:09:29"}]
The following is my curl_call.php file
<?php
$url = 'http://127.0.0.1/testing/list_clients.php';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_HTTPGET, TRUE);
curl_setopt($curl, CURLOPT_HEADER, 0);
//curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
//curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type : application/json',
'Accept: application/json'
));
$clientResult = curl_exec($curl);
if($clientResult == FALSE) {
var_dump(curl_error($curl));
}
curl_close($curl);
var_dump($clientResult); //For this line I am getting the following image eror
$clients = json_decode($clientResult, TRUE);
var_dump($clients);
If I var_dump($clientResult); then I am getting the following error
It's displaying NULL all the time. What might be causing the error.
You are missing a warning being thrown about $ch. It's undeclared, yet you reference it on line 17:
if($clientResult == FALSE) {
var_dump(curl_error($ch));
}
(As a side note, I'd use === FALSE, so valid return values which cast to FALSE don't wrongly trigger that code.)
You're also then carrying on with execution after the error is (failed to be) handled. The NULL you're seeing could be because the curl request failed.
Correct the typo in your code and stop (or do appropriately) if an error is thrown:
if($clientResult == FALSE) {
var_dump(curl_error($curl));
exit();
}
Update in response to the OP being updated:
The other reason NULL might be returned is because the response is not valid json. Check the PHP documentation:
Returns the value encoded in json in appropriate PHP type. Values
true, false and null are returned as TRUE, FALSE and NULL
respectively. NULL is returned if the json cannot be decoded or if the
encoded data is deeper than the recursion limit.
That HTML output you're debugging now shows (in your question update) won't parse as JSON.
Just now figured out. If I comment the following line of code in the curl_call.php it will work fine.
<?php
$url = 'http://127.0.0.1/testing/list_clients.php';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_HTTPGET, TRUE);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
/* curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type : application/json',
'Accept: application/json'
)); */
$clientResult = curl_exec($curl);
if($clientResult == FALSE) {
var_dump(curl_error($curl));
}
curl_close($curl);
var_dump($clientResult);
$clients = json_decode($clientResult);
var_dump($clients);
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.