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 相关文章推荐
用Apache反向代理设置对外的WWW和文件服务器
Oct 09 PHP
不用mod_rewrite直接用php实现伪静态化页面代码
Oct 04 PHP
php 应用程序安全防范技术研究
Sep 25 PHP
php获取后台Job管理的实现代码
Jun 10 PHP
PHP实现视频文件上传完整实例
Aug 28 PHP
php实现curl模拟ftp上传的方法
Jul 29 PHP
PHP开发之归档格式phar文件概念与用法详解【创建,使用,解包还原提取】
Nov 17 PHP
PHP中cookie知识点学习
May 06 PHP
PHP+redis实现的悲观锁机制示例
Jun 12 PHP
php5对象复制、clone、浅复制与深复制实例详解
Aug 14 PHP
Laravel (Lumen) 解决JWT-Auth刷新token的问题
Oct 24 PHP
PHP的垃圾回收机制代码实例讲解
Feb 27 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
开源SNS系统-ThinkSNS
2008/05/18 PHP
php mysql数据库操作分页类
2008/06/04 PHP
php通过ajax实现双击table修改内容
2014/04/28 PHP
PHP实现文件下载详解
2014/11/27 PHP
PHP配置把错误日志以邮件方式发送方法(Windows系统)
2015/06/23 PHP
php使用curl详细解析及问题汇总
2016/08/11 PHP
PHP递归获取目录内所有文件的实现方法
2016/11/01 PHP
PHP编程计算两个时间段是否有交集的实现方法(不算边界重叠)
2017/05/30 PHP
PHP新特性之字节码缓存和内置服务器
2017/08/11 PHP
laravel中的fillable和guarded属性详解
2019/10/23 PHP
javascript函数中的arguments参数
2010/08/01 Javascript
给ListBox添加双击事件示例代码
2013/12/02 Javascript
javascript实现iframe框架延时加载的方法
2014/10/30 Javascript
浅谈JavaScript 框架分类
2014/11/10 Javascript
基于javascript实现根据身份证号码识别性别和年龄
2016/01/22 Javascript
js操作DOM--添加、删除节点的简单实例
2016/07/08 Javascript
cocos creator Touch事件应用(触控选择多个子节点的实例)
2017/09/10 Javascript
webpack引入eslint配置详解
2018/01/22 Javascript
angularjs结合html5实现拖拽功能
2018/06/25 Javascript
JavaScript引用类型RegExp基本用法详解
2018/08/09 Javascript
小程序getLocation需要在app.json中声明permission字段
2019/04/04 Javascript
vue+高德地图实现地图搜索及点击定位操作
2020/09/09 Javascript
JS实现无限轮播无倒退效果
2020/09/21 Javascript
python中pass语句用法实例分析
2015/04/30 Python
python并发编程之多进程、多线程、异步和协程详解
2016/10/28 Python
pycharm 解除默认unittest模式的方法
2018/11/30 Python
解决Django 在ForeignKey中出现 non-nullable field错误的问题
2019/08/06 Python
python创建n行m列数组示例
2019/12/02 Python
英国护发和美妆在线商店:Klip Shop
2019/03/24 全球购物
上班迟到检讨书
2014/09/15 职场文书
党的群众路线教育实践活动个人批评与自我批评
2014/10/16 职场文书
2014年前台接待工作总结
2014/12/05 职场文书
运动会5000米加油稿
2015/07/21 职场文书
2016年教师师德师风心得体会
2016/01/12 职场文书
React Hook用法示例详解(6个常见hook)
2021/04/28 Javascript
python编程实现清理微信重复缓存文件
2021/11/01 Python