将美元兑换成印度卢比

  • 本文关键字:卢比 美元 php
  • 更新时间 :
  • 英文 :


我想将货币从美元转换为印度卢比,以美元为单位的值可从url中检索,我想根据当前汇率将其转换成印度卢比。这是第一个代码:

<?php 
 require_once('currency.php');
 $val=$_GET["val"];
 echo currency($val);
 ?>

第二个代码是:

<?php
function currency($val) {
$amount = $val;
 $url = "http://www.google.com/ig/calculator?hl=en&q=$amountUSD=?INR";
 $ch = curl_init();
 $timeout = 0;
 curl_setopt ($ch, CURLOPT_URL, $url);
 curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch,  CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT  6.1)");
 curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
 $rawdata = curl_exec($ch);
 curl_close($ch);
 $data = explode('"', $rawdata);
 $data = explode(' ', $data['3']);
 $var = $data['0'];
 return round($var,3);
 }
 ?>

顺便说一句,我在免费托管网站0fees.net上测试了这段代码,所以当我尝试实时美元到印度卢比的转换时,这有什么问题吗。

错误在于以下代码:

function currency($val) {
    $amount = $val;
    $url = "http://www.google.com/ig/calculator?hl=en&q=$amountUSD=?INR";
    // ...                                              ^^^^^^^^^^
}

php试图评估变量$amountUSD(根据php的字符串解析规则),但失败了,并发出通知:

PHP Notice:  Undefined variable: amountUSD in usdtoinr.php code on line 3

相反,你应该写:

function currency($val) {
    $amount = floatval($val);
    $url = 'http://www.google.com/ig/calculator?hl=en&q=' . $amount . 'USD=?INR';
    // ...
}

要在将来捕获这些错误,请确保在开发机器上将error_reporting设置为E_ALL | E_STRICT

此外,谷歌查询的结果是一个JSON文档。由于对象中属性的顺序可能会有所不同,因此必须使用适当的JSON解析器(如json_decode)对其进行解析,如下所示:

$data = json_decode($rawdata, true);
$tmp = explode(' ', $data['rhs']);
return floatval($tmp[0]);

一般来说,在用户代理中包含对实际用户代理(例如软件主页)的提示也是一个好主意。

使用此PHP代码

<?php
function currency($from_Currency,$to_Currency,$amount) {
$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 , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$rawdata = curl_exec($ch);
curl_close($ch);
$data = explode('"', $rawdata);
$data = explode('"', $data['3']);
$var = $data[0];
return round($var,3);
}
?>

并将其用于输出,当您输入任何金额时,它将从美元转换为印度卢比

<?php 
 require_once('currency.php');
  $amount=@$_GET["val"];
$from='USD';
$to='INR';
 echo currency($from,$to,$amount);
 ?>
<form method="get" ><input name="val" type="text"><input type="submit" value="Submit"></form>

最新更新