These are the steps I want to do:
Get the HTML code of http://www.skyscanner.es/ , a search of flights.
Get only some part of that HTML: a specific "span" which has the price.
Operate with it.
This is the PHP code what I do:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.skyscanner.es/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, "from=Bilbao (BIO)&to=Barcelona (BCN)&depdatetext=25/03/2013&sc_returnOrOneWay=2");
$output = curl_exec($ch);
curl_close($ch);
echo $output;
?>
But I get a strange string like this:
‹¥TkoÚ0ý^‰ÿpTi“ê< t%<¤RuR»U+{}4ñ…X5qf›×Pÿûì$ZõÛ‚Äu¬sî=çú:ýÓ믣Éï‡1¤f!àáû§»Ï#ðHül‚àzr ¿n'÷wù!<Åã/x©1yëõÚ_·}©æÁä[°qY"G«–DŸæ 'ý¢Êf!2=x#CÔívKb FÊ\\ ¡àÐÿ,ùjàdf03d²Íу¤|x7&pì$)UÍ€kI®®:]yKe¸8¼;#àv2y€ª),520h’ Ö`R®!§s3i€ !×Èü~Pòm"m¶ÁXUÝDëBô)!“©dÛÝ‚ª9Ïâ°7³‰æ1ö?à¢|ÑÛø*F3z§ânQ¬ÐðÄîhši¢QñYoJ“§¹’ËŒÅÍqñôž'3Ž‚Y“»œ2ƳyBÔÉ7…îÏ®zÏÐ8I£Ý¡~Ë¿°ja‰RÅÍ››—/m!£BêkähÚ§ÌÛ~nÐEýÐýö´0¬iMw¨¨vkÎLw/ÏêeoæÒ&iA^ôÌ3 §Ë$E÷Þ9Ô=<êØ‘3{uûHµß)gºYMÏî…[1—š.³X¡ †¯Ð¡ý M\¤<³FŽÏÆ•{mŒ™ÇWö0öÆ\{ÞÎNˆ bµ¿nœ\d|œÙ›SôÐöÓhøˆÊÎ0Œ•’Ê2¢a?°°ct¥ÙM'›‰ Z×û/6á~¦úië?®Š%—IÚÃIŠ%h+—#‚òÉöfRAB3Gœ"0®sA·¶Àj+Í€g+*8ûH%ƒwµ”÷°¦ú Ç\ä¦ÒåÊ·¿Aí¨îK÷m-¾vñà-ú¡
So, I have not even passed the first step!
I tried to fix it in several ways but I don't know yet what I am doing wrong. I imagine that can be:
The request because I don't add how much adult, children...
The CURLOPT_URL has to be www.skyscanner.es/search.html as the form has in the action.
Not do a POST request, do an cURL directly to an URL like http://www.skyscanner.es/flights/bio/bcn/130325/airfares-from-bilbao-to-barcelona-in-march-2013.html?flt=1
Please can anyone help me?
Thanks in advance!
Edited: I've changed the title, is closer to the problem I have now.
It doesn't matter what message is encoded in the body since you're receiving:
HTTP/1.1 405 Method Not Allowed
which means you can't use POST.
If you'll read all the headers of the response you'll see that one of them says:
Allow: GET, HEAD, OPTIONS, TRACE
If you'll remove the two lines:
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, "from=Bilbao (BIO)&to=Barcelona (BCN)");
and change:
curl_setopt($ch, CURLOPT_URL, "http://www.skyscanner.es/");
into:
curl_setopt($ch, CURLOPT_URL, "http://www.skyscanner.es/vuelos/bio/bcn/130325/tarifas-de-bilbao-a-barcelona-en-marzo-2013.html");
It'll work.
Checkout the following code:
<?php
$accept = array(
'type' => array('application/rss+xml', 'application/xml', 'application/rdf+xml', 'text/xml'),
'charset' => array_diff(mb_list_encodings(), array('pass', 'auto', 'wchar', 'byte2be', 'byte2le', 'byte4be', 'byte4le', 'BASE64', 'UUENCODE', 'HTML-ENTITIES', 'Quoted-Printable', '7bit', '8bit'))
);
$header = array(
'Accept: '.implode(', ', $accept['type']),
'Accept-Charset: '.implode(', ', $accept['charset']),
);
$encoding = null;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.skyscanner.es/vuelos/bio/bcn/130325/tarifas-de-bilbao-a-barcelona-en-marzo-2013.html?flt=1");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// curl_setopt ($ch, CURLOPT_POST, 1);
// curl_setopt ($ch, CURLOPT_POSTFIELDS, "from=Bilbao (BIO)&to=Barcelona (BCN)");
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$response = curl_exec($ch);
curl_close($ch);
if (!$response) {
// error fetching the response
} else {
echo $response;
}
?>
I thought that it was using POST method because I get a page whithout prices.
Now I realize that the URL were relatives, so scrips were not loaded. I've add base tag.
[code before]
$result = str_replace("<head>", "<head><base href=\"$skyScannerURL\" />", $response);
Now it has styles and try to load something, but it enter in a bucle, the page is reloaded and the URL has a parameter increasing, it is: ?crty=107
The full code:
$accept = array(
'type' => array('application/rss+xml', 'application/xml', 'application/rdf+xml', 'text/xml'),
'charset' => array_diff(mb_list_encodings(), array('pass', 'auto', 'wchar', 'byte2be', 'byte2le', 'byte4be', 'byte4le', 'BASE64', 'UUENCODE', 'HTML-ENTITIES', 'Quoted-Printable', '7bit', '8bit'))
);
$header = array(
'Accept: '.implode(', ', $accept['type']),
'Accept-Charset: '.implode(', ', $accept['charset']),
);
$encoding = null;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.skyscanner.es/vuelos/bio/bcn/130325/tarifas-de-bilbao-a-barcelona-en-marzo-2013.html?flt=1");
//curl_setopt($ch, CURLOPT_URL, "http://www.skyscanner.es/flights/bio/bcn/130325/airfares-from-bilbao-to-barcelona-in-march-2013.html?flt=1");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$response = curl_exec($ch);
curl_close($ch);
if (!$response) {
// error fetching the response
} else {
$skyScannerURL = 'http://www.skyscanner.es/';
$result = str_replace("<head>", "<head><base href=\"$skyScannerURL\" />", $response);
echo $result;
}
You can see online here: codepad.viper-7.com
Obvious something is not working well.
Thanks again everyone.
Related
I have a CURL code that I use to integrate with GetResponse and I thought ill go ahead and copy/paste it for slack too. For some reason there are no errors at all yet slack is empty of requests (a POST to this URL with Postman works just fine). What am I missing? I couldn't find a solution the whole night.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
function slackReporting($data)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://hooks.slack.com/services/XXXX/XXXX/XXXXXX');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
}
$slackReporting_data = array(
'text' => "`New Lead` `+34 today`.",
'username' => "Leads",
'mrkdwn' => true
);
$slackReporting_res = json_decode(slackReporting($slackReporting_data));
$slackReporting_error = "";
if(empty($slackReporting_res->error)){
echo "OK";
} else {
$slackReporting_error = $slackReporting_res->error->message;
}
echo $slackReporting_error;
?>
I always get an OK.
Since you din't return anything from function so you are getting nothing inside $slackReporting_res .Do like below:-
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
function slackReporting($data)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://hooks.slack.com/services/XXXX/XXXX/XXXXXX');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($ch);
if(curl_errno($ch)){
echo 'Request Error:' . curl_error($ch);exit;
}
curl_close($ch);
return $content;
}
$slackReporting_data = array(
'text' => "`New Lead` `+34 today`.",
'username' => "Leads",
'mrkdwn' => true
);
$slackReporting_res = json_decode(slackReporting($slackReporting_data));
var_dump ($slackReporting_res); //check output and work accordingly
?>
And now Op's got error and solved through this link(mentioned by OP in comment):-
PHP - SSL certificate error: unable to get local issuer certificate
Here is a simple example of how to use slack with curl
<?php
define('SLACK_WEBHOOK', 'https://hooks.slack.com/services/xxx/yyy/zzz');
function slack($txt) {
$msg = array('text' => $txt);
$c = curl_init(SLACK_WEBHOOK);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, array('payload' => json_encode($msg)));
curl_exec($c);
curl_close($c);
}
?>
Snippet taken from here
I'm trying to submit a new paste to Paste.ee API using Curl, but the response is always Whoops, looks like something went wrong.
Here's the guideline of Paste.ee API: https://paste.ee/wiki/API:Basics
Here's how my simple code looks like:
<?php
$key = '56b3f127d65445c0cf6ff05f62ffba53';
$format = 'JSON';
$description = 'just for testing';
$paste = 'Just a simple test';
if(function_exists('curl_init')) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://paste.ee/api");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Expect:"));
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, array("key" => $key, "format" => $format, "description" => $description, "paste" => $paste));
$response = curl_exec($ch);
curl_close($ch);
echo $response;
} else {
error_log("You need cURL to use this api!");
}
?>
I've double-checked, my key is right.
I'm new to Curl, so any advice would be very appreciated.
Thanks.
It's because "format" is case sensitive in which it must small letters
You your format is capitalised which is it should be small letters
"format": "json"
look
$key = '56b3f127d65445c0cf6ff05f62ffba53';
$format = 'JSON';
$description = 'just for testing';
$paste = 'Just a simple test';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://paste.ee/api");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Expect:"));
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'key' => $key,
'format' => $format,
'description' => 'just for testing',
'paste' => $paste,
'format' => 'json'
));
CAPITALISED WHICH RETURNS ERROR
small letters which returns the correct json data
I'm trying, without success, to get some results using Bing's Image search API without HTTP/Request2.php component (as used in the official examples).
I understand that the only two required parameters to make a very primitive call are q which is the query string and the subscription key. The key must be sent using headers. After looking around I found this very simple example to send headers with PHP:
$sURL = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=cats";
$aHTTP = array(
'Ocp-Apim-Subscription-Key' => 'xxxxxxx',
);
$context = stream_context_create($aHTTP);
$contents = file_get_contents($sURL, false, $context);
echo $contents;
But it does not output anything. Would you kindly help me with a very basic example of use of Bing's API?
SOLVED
Thanks to Vadim's hint I changed the way headers are sent and now output is a Json encoded result. (Remember to add your API subscription key.)
$sURL = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=cats";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sURL);
curl_setopt($ch, CURLOPT_TIMEOUT, '1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: multipart/form-data',
'Ocp-Apim-Subscription-Key: xxxxx'
));
$content = curl_exec($ch);
echo $content;
Just another tip. The syntax of query filters and other parameters change form version to version. For example the following work correctly in version 5.0:
To search only for JPEG images of cats and get 30 results use:
q=cats&encodingFormat='jpeg'&count=30
To search only for 'portrait' aspect images with size between 200x200 and 500x500 use:
q=cats&aspect=Tall&size=Medium
Try using cURL
$sURL = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=cats";
$key = "xxxxxxx";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sURL);
curl_setopt($ch, CURLOPT_TIMEOUT, '1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 'ocp-apim-subscription-key:$key');
$content = curl_exec($ch);
echo $content;
Here is my working code..
Replace ******** with your bing subscription key.
$sURL = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=microsoft-surface&count=6&mkt=en-US";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: multipart/form-data',
'Ocp-Apim-Subscription-Key: *******************'
));
$contents = curl_exec($ch);
$myContents = json_decode($contents);
if(count($myContents->value) > 0) {
foreach ($myContents->value as $imageContent) {
echo '<pre/>';
print_r($imageContent);
}
}
I need to attach a pdf file form local drive and post it to the API using PHP CURL.
Here is the RingCentral FaxOut API Documentation
$url = "https://service.ringcentral.com/faxapi.asp";
$data = array(
'Username' => 'XXXXXXXXX',
'Password' => 'XXXXXXXXX',
'Recipient' => 'XXXXXXXXXX|Navneet',
'Coverpage' => 'Default',
'Coverpagetext' => 'Testing Faxout API ',
'Resolution' => 'High',
"Sendtime" => date('d:m:y H:i:s'),
'Attachment' => file_get_contents(PATH_TO_FILE)
);
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch,CURLOPT_POST, count($data));
curl_setopt($ch,CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
API do not return anything in response. I think, I'm not sending the attachment properly. The attachment should be in binary stream. I tried base64_encode but no success.
As given in the Request body example, header for attachment should be like this
Content-Disposition: form-data; name="Attachment"; filename="C:\example.doc"
<Document content is here>
-----------------------------7d54b1fee05aa
You can POST anything to the api with CURL, $doc in my example is anything you want to post , it can be a json_encoded file , a base64_encoded image or pdf or anything else.
$baseUri = https://service.ringcentral.com/faxapi.asp;
$doc = file_get_contents(PATH_TO_FILE);
$ci = curl_init();
curl_setopt($ci, CURLOPT_URL, $baseUri);
curl_setopt($ci, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ci, CURLOPT_FORBID_REUSE, 0);
curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ci, CURLOPT_POSTFIELDS, $doc);
// also you can specify any specific header like this :
$h1['Content-Disposition'] = 'Content-Disposition'. ': ' . 'form-data'; // headers are key-value pairs right ?
curl_setopt($ci, CURLOPT_HTTPHEADER, array_values($h1)); // you can use this line for each header as a new key-value pair
$h2['name'] = 'name'. ': ' . 'Attachment';
curl_setopt($ci, CURLOPT_HTTPHEADER, array_values($h2));
$h3['filename'] = 'filename'. ': ' . 'C:\example.doc';
curl_setopt($ci, CURLOPT_HTTPHEADER, array_values($h3));
$response = curl_exec($ci);
**NOTE ** : its a good Idea to first of all check to see if your file_get_contents function works :
so in another php file check to see this :
echo file_get_contents(PATH_TO_FILE);
See if it echoes correctly
This is the function and how I generated the info for the request
function send_curl_request_with_attachment($method, $headers, $url, $post_fields) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
if($headers != "" && count($headers) > 0){
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
} curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_VERBOSE,true);
$result = curl_exec($ch);
curl_close($ch);
return $result;}
$token_slams = "Authorization: Bearer " . $access_token;
$authHeader = array(
$token_slams,
'Accept: application/form-data');
$schedule_path ='../../documents/' . $docs_record["document"];
$cFile = curl_file_create($schedule_path);
$post = array(
'old_record' => $old_record,
'employer_number' => $employer_number,
'payment_date' => $payment_date,
'fund_year' => $fund_year,
'fund_month' => $fund_month,
'employer_schedule'=> $cFile
);
send_curl_request_with_attachment("POST", $authHeader, $my_url, $post);
Here is my code:
$ch = curl_init('');
$request = 'where={"place":"'.$place.'"}&count=1&limit=0';
$url = "https://api.parse.com/1/classes/className" . "?" . $request;
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'X-Parse-Application-Id: ...',
'X-Parse-REST-API-Key: ...
));
//curl_setopt($ch, CURLOPT_POST, true);
// Execute
$result = curl_exec($ch);
// Close connection
curl_close($ch);
Here is the output:
{"results":[],"count":0}
I want to get only he number in count.
I tried this:
$json_res = json_decode($result, true);
echo 'Number : '.$json_res['count'];
but the output becomes:
Number :
If i do json_encode the result is just a True value.
I tried added this:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
but didn't change anything.
What am I missing?
EDIT: doing a var_dump on $json_res gives me that: int(1).
Why is that?
Curl does not return the output if you don't set the CURLOPT_RETURNTRANSFER option
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);