I am new to the Visa Developer Platform (VDP) APIs and I am running into issues trying to read the output of the response as a json using php. I followed the tutorial here. I am using the Offers Data API.
My goal is to be able to generate a list of deals to be displayed in the frontend. I am trying to do this by reading the json output and parsing the info for the deals.
This is what the original tutorial had and it works fine:
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_PORT, 443);
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($curl, CURLOPT_SSLVERSION, 1);
curl_setopt($curl, CURLOPT_SSLCERT, $cert);
curl_setopt($curl, CURLOPT_SSLKEY, $key);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "$username:$password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($curl); //This output contains the json output as well
$response_info = curl_getinfo($curl);
To get the information, I am running: $response_data = file_get_contents($response); which does not appear to work. Since the output it not just the json, but with other info, I am not able to run: $arr = json_decode($response,true); to parse the json. This is what the json looks like:
{"ReturnedResults":4,"StartIndex":1,"Offers":[{"indexNumber":1,"offerContentId":105515,"offerId":
and so on. The json starts with {"indexNumber":1 and everything before it needs to be discarded.
Please let me know what I can do to fix this, or if there is a better way to accomplish the goal. Thank you!
Goal
The json starts with {"indexNumber":1 and everything before it needs to be discarded. Please let me know what I can do to fix this, or if there is a better way to accomplish the goal.
Code
The response variable contains a valid json object. Since you only need Offers you can use this code to obtain the Offers:
$response = '{"ReturnedResults":4,"StartIndex":1,"Offers":[{"indexNumber":1,"offerContentId":105515,"offerId":""}]}';
$json = json_decode($response, true);
var_dump($json['Offers']);
Output
array(1) {
[0]=>
array(3) {
["indexNumber"]=>
int(1)
["offerContentId"]=>
int(105515)
["offerId"]=>
string(0) ""
}
}
Init cURL with CURLOPT_RETURNTRANSFER => true - then you will have your content in $response variable. Without that option, result of curl_exec is always boolean.
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'm using a remote API with cURL and querystrings. The issue I'm having is that I can't see the data being returned to me (which is in XML format). To start, here's my code:
$url = 'https://api.somehost.com/GetRequest.do';
$query = 'User=JohnDoe&Password=ABC123&Function=auth';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$curlresponse = curl_exec($ch);
I know the cURL request is working because if I change the password to something incorrect, I get a response back (can see it using print_r($curlresponse) telling me the password is incorrect.
However, when I enter the correct password, I see nothing when I print_r($curlresponse) yet I know I'm receiving the data because a print_r(curl_getinfo($ch)) shows a larghe download_content_length which is the data I'm expecting. The data I'm expecting back is in XML format. I'm just not sure what I'm missing.
Thank you!
I am trying to update some custom fields using the REST API and PHP/cURL.
I'm wondering if I might have edited something without realizing it, while what I have below "worked" yesterday (I think), it does not work now.
I get varying responses using the different "methods", from:
I get this one using the POST method, as it is uncommented below.
HTTP 405 - The specified HTTP method is not allowed for the requested
resource ().
I get this one if I use the commented-out PUT method, with POST commented out.
{"status-code":500,"message":"Read timed out"}
And this one mixing and matching PUT and POST.
{"errorMessages":["No content to map to Object due to end of input"]}
What am I missing/doing wrong? I am using the following code:
<?php
$username = 'username';
$password = 'password';
$url = "https://example.com/rest/api/2/issue/PROJ-827";
$ch = curl_init();
$headers = array(
'Accept: application/json',
'Content-Type: application/json'
);
$test = "This is the content of the custom field.";
$data = <<<JSON
{
"fields": {
"customfield_11334" : ["$test"]
}
}
JSON;
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// Also tried, with the above two lines commented out...
// curl_setopt($ch, CURLOPT_PUT, 1);
// curl_setopt($ch, CURLOPT_INFILE, $data);
// curl_setopt($ch, CURLOPT_INFILESIZE, strlen($data));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
$result = curl_exec($ch);
$ch_error = curl_error($ch);
if ($ch_error) {
echo "cURL Error: $ch_error";
} else {
echo $result;
}
curl_close($ch);
?>
The problem here is that PHP's cURL API is not particularly intuitive.
You might think that because a POST request body is sent using the following option
that a PUT request would be done the same way:
// works for sending a POST request
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// DOES NOT work to send a PUT request
curl_setopt($ch, CURLOPT_PUT, 1);
curl_setopt($ch, CURLOPT_PUTFIELDS, $data);
Instead, to send a PUT request (with associated body data), you need the following:
// The correct way to send a PUT request
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
Note that even though you're sending a PUT request, you still have to use the CURLOPT_POSTFIELDS
option to send your PUT request body. It's a confusing and inconsistent process, but it's what you've
got if you want to use the PHP cURL bindings.
According to the relevant manual entrydocs, the CURLOPT_PUT option seems to only work for PUTting a file directly:
TRUE to HTTP PUT a file. The file to PUT must be set with CURLOPT_INFILE and CURLOPT_INFILESIZE.
A better option IMHO is to use a custom stream wrapper for HTTP client operations. This carries the
added benefit of not making your application reliant on the underlying libcurl library. Such an
implementation is beyond the scope of this question, though. Google is your friend if you're interested
in developing a stream wrapper solution.
I have been trying to post some variables to a site using POST method, using curl to get some results. I am posting to this link.
http://www.rasta.pk/Lhr/Lhr_Traffic.aspx
At this page you will see a drop down menu .. onchange some values are returned in "Yellow" colored table.
I have monitored this site and trying to get those results by making a post request to that link. But, I am getting "Bad Header" error. I have tried changing things but ubable to find a solution.
Here is my code:
"Canal Bank Rd",
"ScriptManager1 " => "UpdatePanelDDLRoads|DropDownRoads",
"__EVENTARGUMENT" => "",
"__EVENTTARGET" => "DropDownRoads"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerz);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_REFERER, "http://www.rasta.pk/Lhr/Lhr_Traffic.aspx");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
?>
There's too little details presented for us to know for sure.
A guess is that you're doing the wrong kind of post, since when you pass in a hash array to CURLOPT_POSTFIELDS it will do a multipart formpost which might not be what the server expects. Pass in a string instead to make a "normal" POST.
If that is not enough, use LiveHTTPHeaders or similar in a browser to figure out exactly what is sent in a "manual" session and then you make sure that your curl program mimics that operation as closely as possible.
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.