PHP实现货币换算的方法


Posted in PHP onNovember 29, 2014

本文实例讲述了PHP实现货币换算的方法。分享给大家供大家参考。

具体实现代码如下:

<?php 

/* 

* File: CurrencyConverter.php 

* Author: Simon Jarvis 

* Copyright: 2005 Simon Jarvis 

* Date: 10/12/05 

* Link: http://www.white-hat-web-design.co.uk/articles/php-currency-conversion.php 

* 

* This program is free software; you can redistribute it and/or 

* modify it under the terms of the GNU General Public License 

* as published by the Free Software Foundation; either version 2 

* of the License, or (at your option) any later version. 

* 

* This program is distributed in the hope that it will be useful, 

* but WITHOUT ANY WARRANTY; without even the implied warranty of 

* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

* GNU General Public License for more details: 

* http://www.gnu.org/licenses/gpl.html 

* 

*/ 

class CurrencyConverter { 

   var $xml_file = "www.ecb.int/stats/eurofxref/eurofxref-daily.xml"; 

   var $mysql_host, $mysql_user, $mysql_pass, $mysql_db, $mysql_table; 

   var $exchange_rates = array(); 

   //Load Currency Rates 

   function CurrencyConverter($host,$user,$pass,$db,$tb) { 

      $this->mysql_host = $host; 

      $this->mysql_user = $user; 

      $this->mysql_pass = $pass; 

      $this->mysql_db = $db; 

      $this->mysql_table = $tb; 

      $this->checkLastUpdated(); 

      $conn = mysql_connect($this->mysql_host,$this->mysql_user,$this->mysql_pass); 

      $rs = mysql_select_db($this->mysql_db,$conn); 

      $sql = "SELECT * FROM ".$this->mysql_table; 

      $rs =  mysql_query($sql,$conn); 

      while($row = mysql_fetch_array($rs)) { 

         $this->exchange_rates[$row['currency']] = $row['rate']; 

      } 

   } 

   /* Perform the actual conversion, defaults to £1.00 GBP to USD */ 

   function convert($amount=1,$from="GBP",$to="USD",$decimals=2) { 

      return(number_format(($amount/$this->exchange_rates[$from])*$this->exchange_rates[$to],$decimals)); 

   } 

   /* Check to see how long since the data was last updated */ 

   function checkLastUpdated() { 

      $conn = mysql_connect($this->mysql_host,$this->mysql_user,$this->mysql_pass); 

      $rs = mysql_select_db($this->mysql_db,$conn); 

      $sql = "SHOW TABLE STATUS FROM ".$this->mysql_db." LIKE '".$this->mysql_table."'"; 

      $rs =  mysql_query($sql,$conn); 

      if(mysql_num_rows($rs) == 0 ) { 

         $this->createTable(); 

      } else { 

         $row = mysql_fetch_array($rs); 

         if(time() > (strtotime($row["Update_time"])+(12*60*60)) ) { 

            $this->downloadExchangeRates(); 

         } 

      } 

   } 

   /* Download xml file, extract exchange rates and store values in database */ 

   function downloadExchangeRates() { 

      $currency_domain = substr($this->xml_file,0,strpos($this->xml_file,"/")); 

      $currency_file = substr($this->xml_file,strpos($this->xml_file,"/")); 

      $fp = @fsockopen($currency_domain, 80, $errno, $errstr, 10); 

      if($fp) { 

         $out = "GET ".$currency_file." HTTP/1.1rn"; 

         $out .= "Host: ".$currency_domain."rn"; 

         $out .= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8) Gecko/20051111 Firefox/1.5rn"; 

         $out .= "Connection: Closernrn"; 

         fwrite($fp, $out); 

         while (!feof($fp)) { 

            $buffer .= fgets($fp, 128); 

         } 

         fclose($fp); 

         $pattern = "{<Cubes*currency='(w*)'s*rate='([d.]*)'/>}is"; 

         preg_match_all($pattern,$buffer,$xml_rates); 

         array_shift($xml_rates); 

         for($i=0;$i<count($xml_rates[0]);$i++) { 

            $exchange_rate[$xml_rates[0][$i]] = $xml_rates[1][$i]; 

         } 

         $conn = mysql_connect($this->mysql_host,$this->mysql_user,$this->mysql_pass); 

         $rs = mysql_select_db($this->mysql_db,$conn); 

         foreach($exchange_rate as $currency=>$rate) { 

            if((is_numeric($rate)) && ($rate != 0)) { 

               $sql = "SELECT * FROM ".$this->mysql_table." WHERE currency='".$currency."'"; 

               $rs =  mysql_query($sql,$conn) or die(mysql_error()); 

               if(mysql_num_rows($rs) > 0) { 

                  $sql = "UPDATE ".$this->mysql_table." SET rate=".$rate." WHERE currency='".$currency."'"; 

               } else { 

                  $sql = "INSERT INTO ".$this->mysql_table." VALUES('".$currency."',".$rate.")"; 

               } 

               $rs =  mysql_query($sql,$conn) or die(mysql_error()); 

            } 

         } 

      } 

   } 

   /* Create the currency exchange table */ 

   function createTable() { 

      $conn = mysql_connect($this->mysql_host,$this->mysql_user,$this->mysql_pass); 

      $rs = mysql_select_db($this->mysql_db,$conn); 

      $sql = "CREATE TABLE ".$this->mysql_table." ( currency char(3) NOT NULL default '', rate float NOT NULL default '0', PRIMARY KEY(currency) ) ENGINE=MyISAM"; 

      $rs =  mysql_query($sql,$conn) or die(mysql_error()); 

      $sql = "INSERT INTO ".$this->mysql_table." VALUES('EUR',1)"; 

      $rs =  mysql_query($sql,$conn) or die(mysql_error()); 

      $this->downloadExchangeRates(); 

   } 

} 

?>

上面的代码复制到一个新文件并将其保存为CurrencyConverter.php。当你需要转换包含类文件,称为“转换”功能。你需要输入自己的mysql数据库变量如登录详细信息。下面的例子将£2.50英镑转换成美元(美元)。
<?php 

   include('CurrencyConverter.php'); 

   $x = new CurrencyConverter('your_host','your_username','your_password','your_database_name','your_table_name'); 

   echo $x->convert(2.50,'GBP','USD'); 

?>

希望本文所述对大家的php程序设计有所帮助。

PHP 相关文章推荐
PHP正确配置mysql(apache环境)
Aug 28 PHP
web目录下不应该存在多余的程序(安全考虑)
May 09 PHP
php将字符串转化成date存入数据库的两种方式
Apr 28 PHP
PHP防止注入攻击实例分析
Nov 03 PHP
php中curl使用指南
Feb 05 PHP
Yii2框架引用bootstrap中日期插件yii2-date-picker的方法
Jan 09 PHP
php使用glob函数遍历文件和目录详解
Sep 23 PHP
PHP实现求两个字符串最长公共子串的方法示例
Nov 17 PHP
PHP基于redis计数器类定义与用法示例
Feb 08 PHP
thinkphp5 migrate数据库迁移工具
Feb 20 PHP
php字符串倒叙
Apr 01 PHP
PHP设计模式(观察者模式)
Jul 07 PHP
php实现的树形结构数据存取类实例
Nov 29 #PHP
Codeigniter购物车类不能添加中文的解决方法
Nov 29 #PHP
ThinkPHP模版中导入CSS和JS文件的方法
Nov 29 #PHP
ThinkPHP中Session用法详解
Nov 29 #PHP
thinkphp的静态缓存用法分析
Nov 29 #PHP
thinkphp中memcache的用法实例
Nov 29 #PHP
thinkPHP实现瀑布流的方法
Nov 29 #PHP
You might like
使用PHP 5.0创建图形的巧妙方法
2010/10/12 PHP
php安全开发 添加随机字符串验证,防止伪造跨站请求
2013/02/14 PHP
php使用多个进程同时控制文件读写示例
2014/02/28 PHP
PHP中使用gettext解决国际化问题的例子(i18n)
2014/06/13 PHP
PHP中应该避免使用同名变量(拆分临时变量)
2015/04/03 PHP
PHP5.4起内置web服务器使用方法
2016/08/09 PHP
ThinkPHP实现分页功能
2017/04/28 PHP
javascript call方法使用说明
2010/01/11 Javascript
常用Extjs工具:Extjs.util.Format使用方法
2012/03/22 Javascript
js获取下拉列表框中的value和text的值示例代码
2014/01/11 Javascript
javascript中加号(+)操作符的一些神奇作用
2014/06/06 Javascript
node.js开发中使用Node Supervisor实现监测文件修改并自动重启应用
2014/11/04 Javascript
jQuery模拟黑客帝国矩阵效果实例
2015/06/28 Javascript
jQuery实现的个性化返回底部与返回顶部特效代码
2015/10/30 Javascript
jquery过滤特殊字符',防sql注入的实现方法
2016/08/17 Javascript
JavaScript正则表达式和级联效果
2017/09/14 Javascript
Bootstrap标签页(Tab)插件切换echarts不显示问题的解决
2018/07/13 Javascript
Vue父子组件双向绑定传值的实现方法
2018/07/31 Javascript
js神秘的电报密码 哈弗曼编码实现
2019/09/10 Javascript
python实现简单爬虫功能的示例
2016/10/24 Python
浅谈Django的缓存机制
2018/08/23 Python
Python实现CNN的多通道输入实例
2020/01/17 Python
python实现图像拼接功能
2020/03/23 Python
基于Python制作一副扑克牌过程详解
2020/10/19 Python
巴西美妆购物网站:Kutiz Beauté
2019/03/13 全球购物
西铁城美国官方网站:Citizen Watch美国
2019/11/08 全球购物
意大利奢侈品综合电商网站:MODES
2019/12/14 全球购物
商务日语毕业生自荐信
2013/11/23 职场文书
毕业生求职自荐信怎么写
2014/01/08 职场文书
残疾人创业典型事迹
2014/02/01 职场文书
社区平安建设方案
2014/05/25 职场文书
毕业生找工作自荐书
2014/06/30 职场文书
施工单位工程部经理岗位职责
2015/04/09 职场文书
大学校园招聘会感想
2015/08/10 职场文书
致运动员的广播稿
2015/08/19 职场文书
几款流行的HTML5 UI框架比较(小结)
2021/04/08 HTML / CSS