I am using Google’s Calculator API. I have to pass dynamic values to the google url as below:
$url = 'http://www.google.com/ig/calculator?hl=en&q=' . urlEncode($amount . $currency . '=?' . $exchangeIn);
But I am getting the following exception from the google.
Warning: file_get_contents(http://www.google.com/ig/calculator?hl=en&q=13,000,000pkr=?cad) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 503 Service Unavailable in /home/..../public_html/config/config.php on line 48
My function for this is as:
function exchangeRate($amount, $currency, $exchangeIn) {
$url = 'http://www.google.com/ig/calculator?hl=en&q=' . urlEncode($amount . $currency . '=?' . $exchangeIn);
$data = file_get_contents($url);
if(!$data) {
throw new Exception('Could not connect');
}
$json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
$array = $json->decode($data);
if(!$array) {
throw new Exception('Could not parse the JSON');
}
if($array['error']) {
throw new Exception('Google reported an error: ' . $array['error']);
}
return number_format($array['rhs']);
}
echo exchangeRate('9,200,000', 'pkr', 'cad')
Can somebody what is wrong with my code or something wrong with this google api ?
Thanks
I also created currency calculator using Google’s Calculator API like that. Below is my code.
Usage:
simply use your own URL like: yourdomain.com/file.php?from=USD&to=EUR&q=10
The PHP Script:
<?php
session_start();
if(isSet($_GET['from']) && isSet($_GET['to']) && isSet($_GET['q'])) {
$from = preg_replace('/[^A-Z]/','',$_GET['from']);
$to = preg_replace('/[^A-Z]/','',$_GET['to']);
$q = preg_replace('/[^0-9\.]/','',$_GET['q']);
echo currency($from,$to,$q);
}
function currency($from_Currency,$to_Currency,$amount) {
$cookieName = md5("$from_Currency|$to_Currency|$amount");
if(isSet($_COOKIE["$cookieName"])) {
echo $_COOKIE["$cookieName"];
}
else {
$amount = urlencode($amount);
$from_Currency = urlencode($from_Currency);
$to_Currency = urlencode($to_Currency);
$url = "http://www.google.com/ig/calculator?hl=en&q=$amount$from_Currency=?$to_Currency";
$ch = curl_init();
$timeout = 0;
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT , $_SERVER['HTTP_USER_AGENT']);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$rawdata = curl_exec($ch);
curl_close($ch);
$data = html_entity_decode($rawdata);
$data = str_replace(array('lhs','rhs','error','icc',': '),array('"lhs"','"rhs"','"error"','"icc"',':'),$data);
$row = json_decode($data,true);
if(preg_match('/million/',$row['rhs'])) {
$x = 1000000;
}
else if(preg_match('/billion/',$row['rhs'])) {
$x = 1000000000;
}
else {
$x = 1;
}
$result = preg_replace('/[^0-9\.]/','',$row['rhs']);
$kurs = $result * $x;
if($row['icc'] == 'true') {
setcookie("$cookieName", number_format($kurs,2), time()+3600);
return number_format($kurs,2);
}
else {
return "Not available";
}
}
}
?>
Related
I have a script that returns a linked list when provided a URL from an RSS feed. It is on a server running PHP 5.2. The script works fine with other RSS feeds I've provided, but is not working on the following URL.
URL: https://www.nwp.org/rss.csp
<?php
//SETUP THE VARIABLES
if(!strlen($RSSFEED_URL)) { $RSSFEED_URL = $_GET['url']; }
if(!strlen($RSSFEED_LIMIT)) { $RSSFEED_LIMIT = abs($_GET['limit']); }
if(!strlen($RSSFEED_EXCERPT)) { $RSSFEED_EXCERPT = abs($_GET['excerpt']); }
if(!strlen($RSSFEED_DATE)) { $RSSFEED_DATE = abs($_GET['date']); }
if(!strlen($RSSFEED_LINK)) { $RSSFEED_LINK = $_GET['link']; }
//SET DEFAULTS
if($RSSFEED_LIMIT > 15 || !strlen($_GET['limit'])) { $RSSFEED_LIMIT = 5; }
if($RSSFEED_EXCERPT !== 0) { $RSSFEED_EXCERPT = 1; }
if($RSSFEED_DATE !== 0) { $RSSFEED_DATE = 1; }
//CONNECT THE FEED
$ch = curl_init();
curl_setopt($ch, CURLOPT_TIMEOUT, .6);
curl_setopt($ch, CURLOPT_URL, $RSSFEED_URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_HEADER, false);
$RSSFEED_CONTENTS = curl_exec($ch);
$RSSFEED_CONTENTS = preg_replace('/&(?![A-Za-z0-9#]{1,7};)/','&',$RSSFEED_CONTENTS);
curl_close($ch);
if($RSSFEED_CONTENTS){
$RSSFEED = simplexml_load_string($RSSFEED_CONTENTS);
if(!strlen($RSSFEED_LINK)) { $RSSFEED_LINK = $RSSFEED->channel->link; }
if(sizeof($RSSFEED->channel->item) < $RSSFEED_LIMIT){ $RSSFEED_LIMIT = sizeof($RSSFEED->channel->item); }
for($i = 0; $i < $RSSFEED_LIMIT; $i++){
echo '
<p>
'. $RSSFEED->channel->item[$i]->title .'';
if($RSSFEED_EXCERPT){
echo '
<br />' . $RSSFEED->channel->item[$i]->description;
}
if($RSSFEED_DATE){
echo '
<br />' . date("F j h:ia", strtotime($RSSFEED->channel->item[$i]->pubDate));
}
echo '
</p>';
}
echo '
<p class="last" align=right>
<span class="more">
Read More ›
</p>';
}
else{
echo '
<p>RSS Feed Unavailable.</p>';
}
?>
Okay, I figured it out thanks to curl_error(). Looks like the https is what caused the issue. So I added the following to the transfer setup:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
This tells the curl command to not verify the peer's cert.
ok, i think i just fucked up everything because of my brain failure.
I followed Google's example of "phpsqlsearch_v3":
imported the sql file
change the query from showing miles to kilometers
testing by using this:
phpsqlsearch_genxml.php?lat=37.315903&lng=-121.977928&radius=40
everything works as charm...
going into website to get latlong, adding and changing some data in db
now, I'm changing the phpsqlsearch_genxml.php to....
phpsqlsearch_genxml.php?lat=59.627847&lng=17.838589&radius=40
...nothing... however, if i change radius to 8000 it will work but the distance for places around input will be like 5665.231121242624km but if i flip the input because I'm on the right side of the earth blink blink to
phpsqlsearch_genxml.php?lat=17.838589&lng=59.627847&radius=100
it will give me a more accurate result, however... the result should closer and around 1-2km...
suggestion what to do now?
function getAddress($lat, $lng) {
$use_curl = false;
if ($use_curl) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://maps.googleapis.com/maps/api/geocode/json?latlng=" . $lat . "," . $lng . "&sensor=true");
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, Array (
"Content-type: application/binary"
));
curl_setopt($ch, CURLOPT_POST, 1);
$response = curl_exec($ch);
if (curl_errno($ch))
return -1;
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$str = substr($response, $header_size);
curl_close($ch);
$data = json_decode($str, true);
if (isset($data["results"]) && is_array($data["results"])) {
$street = $data["results"][0]["formatted_address"];
$ac = $data["results"][0]["address_components"];
$len = count($ac);
$i = 0;
$city = "";
while ($i<$len) {
if (in_array("locality", $ac[$i]["types"])) $city = $ac[$i]["long_name"];
else if (in_array("country", $ac[$i]["types"])) $city .= ",".$ac[$i]["short_name"];
$i++;
}
$meta = array(
"status"=>200,
"message"=>"Succeed."
);
return array("meta"=>$meta, "response"=>array("address"=>$street, "city"=>$city));
} else {
$meta = array(
"status"=>406,
"message"=>"Address is not known."
);
return array("meta", $meta);
}
} else {
$str = #file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?latlng=" . $lat . "," . $lng . "&sensor=true");
$data = json_decode($str, true);
if (isset($data["results"]) && is_array($data["results"])) {
$street = $data["results"][0]["formatted_address"];
$ac = $data["results"][0]["address_components"];
$len = count($ac);
$i = 0;
$city = "";
while ($i<$len) {
if (in_array("locality", $ac[$i]["types"])) $city = $ac[$i]["long_name"];
else if (in_array("country", $ac[$i]["types"])) $city .= ",".$ac[$i]["short_name"];
$i++;
}
$meta = array(
"status"=>200,
"message"=>"Succeed."
);
return array("meta"=>$meta, "response"=>array("address"=>$street, "city"=>$city));
} else {
$meta = array(
"status"=>406,
"message"=>"Address is not known."
);
return array("meta"=>$meta);
}
}
}
I have following loop to calculate comments and likes
function AddCampaignDetails($next=null){
$AccessToken = ACCESS_TOKEN;
$url = "https://api.instagram.com/v1/tags/canonfanatic/media/recent?access_token=".$AccessToken;
if($url !== null) {
$url .= '&max_tag_id=' . $next;
}
/*//Also Perhaps you should cache the results as the instagram API is slow
$cache = './'.sha1($url).'.json';
if(file_exists($cache) && filemtime($cache) > time() - 60*60){
// If a cache file exists, and it is newer than 1 hour, use it
$jsonData = json_decode(file_get_contents($cache));
}else{
$jsonData = json_decode((file_get_contents($url)));
file_put_contents($cache,json_encode($jsonData));
}*/
$Ch = curl_init();
curl_setopt($Ch, CURLOPT_URL, $url);
curl_setopt($Ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($Ch, CURLOPT_TIMEOUT, 20);
$Result = curl_exec($Ch);
curl_close($Ch);
$Result = json_decode($Result);
$Data = $Result->data;
//echo "<pre>"; print_r($Data); echo "</pre>";
$CommentsSum = 0;
$LikesSum = 0;
for($i=0; $i<count($Data); $i++){
$CommentsSum += $Data[$i]->comments->count;
$LikesSum += $Data[$i]->likes->count;
}
//echo ' Comments '.$CommentsSum;
//echo ' Likes '.$LikesSum;
echo "<br />";
if(isset($Result->pagination->next_url) && !empty($Result->pagination->next_url)){
$next = $Result->pagination->next_url;
$this->AddCampaignDetails($next);
}else{
$NextUrl = "";
die;
}
return $result;
}
After this loop, I have echo $CommentsSum; variable and get this output
183
306
320
42
Now I want above number sum 851.
Any idea?
Thanks.
Your $Data[$i]->comments->count must be a number, and it's seem that is a string, so it's merging string instead of doing math.
And If you really have a new line between each number (like you said in echo) maybe $Data[$i]->comments->count is equal to "183\n"
use for example :
$CommentsSum += intval($Data[$i]->comments->count)
I use the code in php to connect to the api and display the results...
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
require("OAuth.php");
$cc_key = "cc_key"; //cc_key
$cc_secret = "cc_secret"; // cc_secret key
$url = "https://yboss.yahooapis.com/ysearch/web";
$args = array();
$args["q"] = htmlspecialchars($_GET["q"]);
$args["format"] = "json";
$consumer = new OAuthConsumer($cc_key, $cc_secret);
$request = OAuthRequest::from_consumer_and_token($consumer, NULL,"GET", $url, $args);
$request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, NULL);
$url = sprintf("%s?%s", $url, OAuthUtil::build_http_query($args));
//echo $url . "<br>"; test uri
$ch = curl_init();
$headers = array($request->to_header());
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$rsp = curl_exec($ch);
$results = json_decode($rsp, true);
//force to assoc-array, which will allow array-access
foreach($results['bossresponse']['web']['results'] as $result)
{
//$result is array here, but do the same stuff
echo '<a href="'.$result['url'].'" target=\'_blank\'>'.$result['title'].'</a></br>';
echo ''.$result['abstract'].'</br>';
echo '<a href="'.$result['url'].'" target=\'_blank\'>'.$result['dispurl'].'</a></br>';
}
?>
then write mini "pagination"
//$start = "&start=" . "0";
$start_val = $_GET['start'];
if ($start_val == "") $start_val = 0;
$start = "&start=" . $start_val;
// Some more code...
$count_val = 10;
$count = "&count=" . $count_val;
if ($query != "") {
if ($start_val != 0) {
echo 'previous';
echo '<span> | </span>';
}
echo 'next';
}
but "pagination" does not work =(
I can not understand why does not work
My question is how do I paginate results, since all the 50 results appear on the first web page only. I want to display ten results in every page.
Please HELP me
Thanks.
Here is the code I have, I cannot work out what is causing the delays?
To load the remote URL it doesn't take more than a second, should I pass a user_agent?
Please excuse if this is a stupid question, I'm new to PHP, would it be worth setting a timeout as part of the curl request?
<?php
$url = $_GET['url'];
if(!filter_var($url, FILTER_VALIDATE_URL)) {
?>
{"errors":1,"message":"The URL was not valid"}
<?php
die();
}
$p=parse_url($url);
$baseurl = $p['scheme'] . '://' . $p['host'];
$path_parts = pathinfo($url);
$current_dir = $path_parts['dirname'];
Function check_img($file) {
$x = #getimagesize($file);
if ($x) {
switch ($x['mime']) {
case "image/gif" || "image/jpeg" || "image/png":
$response = true;
break;
default:
$response = false;
break;
}
} else {
$response = false;
}
return $response;
}
function ranger($url){
$headers = array(
"Range: bytes=0-605768"
);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$data = curl_exec($curl);
curl_close($curl);
return $data;
}
function file_get_contents_curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$html = file_get_contents_curl($url);
//parsing begins here:
$doc = new DOMDocument();
#$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('title');
// Get all image tags
$imageTags = $doc->getElementsByTagName('img');
$numImages = $doc->getElementsByTagName('img')->length;
//get and display what you need:
$metas = $doc->getElementsByTagName('meta');
for ($i = 0; $i < $metas->length; $i++)
{
$meta = $metas->item($i);
if($meta->getAttribute('property') == 'og:image' || $meta->getAttribute('name') == 'og:image')
$fb_image = $meta->getAttribute('content');
$fb_image = isset($fb_image) ? $fb_image : '';
}
?>
{
"resource_images": {
"url" : "<?php echo $url?>",
"baseurl" : "<?php echo $baseurl?>",
"fb" : "<?php echo $fb_image?>",
"images" : [<?php
$i = 0;
$image_results = array();
$numItems = count($imageTags);
if ($fb_image !== '') {
$image_results[] = $fb_image;
}
foreach($imageTags as $tag) {
if ($i >= 25) {
break;
}
if (substr($tag->getAttribute('src'),0,4) === 'http') {
$img = $tag->getAttribute('src');
} elseif (substr($tag->getAttribute('src'),0,1) === '/') {
$img = $baseurl . $tag->getAttribute('src');
} else {
$img = $current_dir . $tag->getAttribute('src');
}
$exists = check_img($img);
if ($exists) {
$raw = ranger($img);
$im = imagecreatefromstring($raw);
$width = imagesx($im);
$height = imagesy($im);
if ($width > 300) {
$image_results[] = str_replace('"', "", $img);
}
if(++$i < $numItems && ++$i < 25) {
echo ",";
}
}
}
$i = 0;
foreach($image_results as $img_url) {
?>
{
"url" : "<?php echo str_replace('"', "", $img_url);?>",
"count" : <?php echo count($image_results)?>
}
<?php
if(++$i < count($image_results) && $i < 15) {
echo ",";
}
}?>
]
}
}
use this at the beginning:
set_time_limit(0)
Yes, definately a timeout on the curl, as this can go on forever.
What I would do in this case is to pinpoint the code that is taking up alot of the time like this:
<?php
function microtime_float() {
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$time_start = microtime_float(); //this # the top of ur file
// process some code
// ...
// show results, this can be anywhere, inside a function, loop etc,
$time_end = microtime_float();
$time = $time_end - $time_start;
echo "Did it in $time seconds\n . <br>";
I wouldnt time the whole script but go part by part and find out where the wait is.