How to parse Curl response? - php

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);

Related

PHP CURL POST data with value empty

I have this code to POST data to an url that is receiving the data with below, with content-type header set as text/html
file_get_contents("php://input");
This is the code That I used to POST to url and it is sending the data, but without values (i'm sending an array data with key values).
$url = "http://url im sending data to";
$object = array(
"key1" => "123",
"key2" => "345",
"key3" => "567"
);
$data = http_build_query($object, '', '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTREDIR, 3);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
However, it's sending the data, but without the values, since I get a response back from the url saying that values are empty.
Moreover, I checked the curl_errno($ch) and it doesn't return anything so there is no error within my code (I think?)
Can someone help me out?!
Thanks in advance!
OK I solved the problem and it was pretty simple.
Just swap the http_build_query with json_encode, and make sure to only set the curl_setopt as it is.
add the bottom code also.
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
I don't know why but for some reason, if I add other curl_setopt variables like
curl_setopt($ch, CURLOPT_POST, true);
it does not work.

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.

How to force abstract JSON data only from an API response?

Description
I'm trying to make a request to an API via PHP cURL
$access_token = $tokens['access_token'];
$headers = array(
"Authorization: Bearer " . $access_token
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,env('USER_INFO'));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 1000);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
curl_setopt($ch, CURLOPT_ENCODING , "gzip");
curl_setopt($ch, CURLOPT_USERAGENT,'php');
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
$info = curl_getinfo($ch);
$userInfo = curl_exec($ch);
$userInfo = json_decode($userInfo, true);
dd($userInfo);
I kept getting this back
{"sub":"acr:123;type=STAT","updated_at":1509463516,"name":"User","email":"user#email.com"}
1
Try #2
If I do
$userInfo = json_encode($userInfo, true);
I got
{"sub":"acr:123;type=STAT","updated_at":1509463516,"name":"User","email":"user#email.com"}
"true"
How do I get rid of the 1 or true below it, and only get the JSON data?
Is there another param for json_decode() that I need to pass in?
Set the CURLOPT_RETURNTRANSFER curl option. curl_exec is just returning true without that, (it echoes the response and returns true; see curl_exec return values) and json_decode(true) is true.
How would one go about and debug this further?
A couple of things to experiment with:
Remove $userInfo = json_decode($userInfo, true); and
dd($userInfo);. Without the CURLOPT_RETURNTRANSFER option set, you should still see the non-decoded JSON, but not the true or 1.
Add another dd($userInfo); before the json_decode. You'll see what curl_exec actually returned, which may help you eliminate json_decode as a possible cause for this odd looking behavior.
The following line should solve your problem with the response.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

how to call an api via php and get a json file from it

I want to check all of the requested urls and if the url contains "video" folder in it, redirect it to an API file. then the API gives me a json files which only contains "respond:true" or "respond:false". In case of having respond:true in the json file the url must be showed and if the json file contains respond:false a predefined simple 403 page must be showed to the user.
I know that the fist part is possible with a simple code in .htaccess file like this:
RewriteRule ^your/special/folder/ /specified/url [R,L]
But I don't know how to do the second part. I mean how to get the result of API, which is in form of a json file and check it.
You can use CURL..
GET REQUEST
$url = 'http://example.com/api/products';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response_json = curl_exec($ch);
curl_close($ch);
$response=json_decode($response_json, true);
POST REQUEST
$postdata = array(
'name' => 'Arfan'
);
$url = "https://example.com/api/user/create";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
You can also use file_get_content to get API data.
$json = file_get_contents("$url")
You can execute second part (Calling API and response): Call API using curl and process based on its response:
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_URL, "api_url_here");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$api_response_json = curl_exec($ch);
curl_close($ch);
//convert json to PHP array for further process
$api_response_arr = json_decode($api_response_json);
if($api_response_arr['respond'] == true ){
//code for success here
}else{
// code for false here
}
Please note: Json response from API is depend on API Response, If API is giving response in json format ( can be based on params also ).

(cURL / PHP) API Response - Invalid HTTP method used

Hopefully a simple question, I have tried to connect to my first REST API using PHP and cURL. My code is as follows:
<?php
$zooplaKey = "mykey";
$postcode = $_GET['postcode'];
$sendData = array('api_key' => $zooplaKey,
'postcode' => $postcode,
'output_type' => "postcode");
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, 'http://api.zoopla.co.uk/api/v1/average_area_sold_price.js');
curl_setopt($curl, CURLOPT_POSTFIELDS, $sendData);
//curl_setopt($curl, CURLOPT_POST, true);
//curl_setopt($curl, CURLOPT_HTTPGET, true);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$raw_json = curl_exec($curl);
curl_close($curl);
$zooplaInfo = json_decode($raw_json, true);
echo "<pre>";
print_r($zooplaInfo);
echo "</pre>";
?>
Run exactly as above I get a return of:
Array
(
[error_string] => Invalid HTTP method used
[error_code] => 2
)
Uncommenting //curl_setopt($curl, CURLOPT_POST, true); or //curl_setopt($curl, CURLOPT_HTTPGET, true); just returns a blank screen.
By using the following URL I am able to get a valid result (obviously I have had to blank the api key so this link is for structure purposes only) http://api.zoopla.co.uk/api/v1/average_area_sold_price.xml?api_key=mykey&postcode=ws12dn&output_type=postcode
Thanks all.
According to the Zoopla API Documentation, what you are trying to do is to:
Retrieve the average sale price for houses in a particular area.
Retrieval is done using a GET method in the REST standard. By using CURLOPT_POSTFIELDS, cURL will automatically convert your request to a POST, which is invalid for retrieval. You should remove the post fields part, and do that instead:
curl_setopt($curl, CURLOPT_URL, 'http://full/url?'.http_build_query($sendData));
The parameters in the URL are being passed as GET. I would try appending the parameters to the CURLOPT_URL instead of putting them in the CURLOPT_POSTFIELDS array. The remote service probably requires the values be in the query string rather than being posted.

Categories