SitePoint Sponsor

User Tag List

Page 1 of 2 12 LastLast
Results 1 to 25 of 47
  1. #1
    SitePoint Wizard
    Join Date
    Jun 2005
    Posts
    1,428
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Currency changer ?

    At the moment I have lots of prices on various pages of loads of items, priced in Euros, Pounds and US Dollars and it is a massive problem to keep changing the prices to reflect currency changes. The price in Euros always stay the same.

    What I would like to run by you good people, is how about if I inputted the currency rates somewhere on a daily basis and then on all of the pages where the prices are, it was coded something like :

    Euros 123,456

    Pounds (multiply the Euros amount above by whatever is on the relevant currency page)

    US Dollars (multiply the Euros amount above by whatever is on the relevant currency page)

    Any help very much appreciated.

    Dez.

  2. #2
    Non-Member Icheb's Avatar
    Join Date
    Mar 2003
    Location
    Germany
    Posts
    1,474
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You store the currency rate in a database and then you do something like

    PHP Code:
    echo '$'$iteminfo['price'] * $currencyrate['dollar']; 

  3. #3
    SitePoint Member
    Join Date
    Jan 2006
    Posts
    5
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    One way - not elegant and code is not pretty or efficient, but should work ...

    Use db table or create writeable file (e.g. /tmp/rates.php) to hold the current exchange rate in format like:
    Code:
    $currency['GBP']="1.00";
    $currency['EUR']="1.46";
    $currency['USD']="1.86";
    Set cron job to get daily rates (change frequency if appropriate) and update the file from yahoo or other provider, e.g.
    Code:
    19 00 * * * /usr/local/bin/php  [path]/currency_rates.php
    currency_rates.php (getting rates against British Pound):
    Code:
    $type = array("GBP", "EUR", "USD");
    foreach($type AS $k=>$v)
    {
    $currency[$v]=file("http://quote.yahoo.com/m5?a=1&t={$v}&s=GBP");
    }
    [code here to update db or file]
    Use cookie to save user preference for currency, with some clickable icons to change that preference.

    Then you can add code wherever you display prices to do the conversion to user's preferred currency. Probably best to point out that prices are indicative rather than definitive or you get into trouble.



    Kevin Holdridge
    Kent House
    www.kenthouse.com

  4. #4
    SitePoint Wizard
    Join Date
    Jun 2005
    Posts
    1,428
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Many thanks Kevin and Icheb, the input is appreciated.

    There's no databases involved at all - is it possible to do it without any database involvement at all please ?

    Dez.

  5. #5
    SitePoint Member
    Join Date
    Jan 2006
    Posts
    5
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Fuller version

    Here's a fuller version using text file instead of database. This version also gets its data via xml from the European Central Bank - probably a more robust approach than scraping html from Yahoo.

    Code lacks any kind of error trapping - recommend you add some.

    Save the code below as [path]/converter.php


    Enjoy.

    Kevin
    www.kenthouse.com

    Code:
    <?php
    /*
    	File: Currency exchange rate updater
    	Author: Kevin Holdridge, wwww.kenthouse.com
    	Last modified: 11 May 2006
    
    	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
    	included GNU General Public License for more details. If you 
    	received this file without the gpl.txt file, you may view it at:
    	http://www.gnu.org/copyleft/gpl.html
    */
    
    /*
    	-----------------------------
    	Requirements & instructions:
    	-----------------------------
    	- Need PHP4.1+
    	- Must be able to set cron jobs
    	- Must be able to set 777 permissions on a text file to allow server to update the file holding the rates
    	- If you don't have PHP available on commandline, you'll need to alter the cron job to use CURL or another way of simulating http
    
    	- create empty text file to hold the rates data, and set permissions, e.g.:
    		touch /tmp/rateslist.php
    		chmod 0777 /tmp/rateslist.php
    	
    	- Configure and save this file as [path]/converter.php
    	- Sample cron entry to update the rates daily:
    	06 00 * * * /usr/local/bin/php [path]/converter.php
    
    	- The first time this script runs, it will populate the local file with a list of currencies and rates
    	
    	- Include the following code near the top of any file that displays price data in order to get the rate or rates into an array ($conversion_rates)
    	<?php
    		$conversion_rates = array();
    		$handle = @fopen($ratesfile, "r");
    		if ($handle) 
    		{
    		   while (!feof($handle)) 
    		   {
    			   $buffer = fgets($handle, 4096);
    			   $pieces = explode(":", $buffer);
    			   $key = $pieces[0];
    				$conversion_rates[$key]['label'] = $pieces[1];
    				$conversion_rates[$key]['rate'] = $pieces[2];
    		   }
    		   fclose($handle);
    		}
    
    		function docurconversion($val)
    		{
    			global $conversion_rates;
    
    			foreach($conversion_rates AS $k=>$v)
    			{
    				if($k)
    				{
    					$newfigure =  number_format($val * $v['rate'], 2, '.', ',');
    					echo "{$v['label']}{$newfigure} ";
    				}
    			}
    		}
    	?>
    
    	- You can then convert or add occurrences of a price in your base currency to one or more alternative currencies
    	- e.g.
    		instead of
    		<?php
    			$a_figure = 5.50;
    			echo "($a_figure}";
    		?>
    		use
    		<?php
    			$a_figure = 5.50;
    			docurconversion($a_figure);
    		?>
    */
    
    /*
    	--------------------
    	CONFIGURATION BLOCK
    	--------------------
    */
    	//Location of remote xml file  ... uisng European Central Bank in this case
    	$sourceurl="http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml";
    
    	//Array of alternative currencies to cover (include currency code and html entity for currency label) 
    	//... open the above xml file to get a list of supported currencies and their codes 
    	$currencies = array(
    		'GBP' => '&pound;',
    		'USD' => 'US$',
    		'AUD' => 'AUS$',
    		'CAD' => 'Canadian$',
    		'EUR' => ''
    	);
    
    	//Your base currency ... use proper currency code (see above, must exist in remote xml file)
    	$base_currency = 'GBP';
    
    	//Adjustment factor ... you pay more than the bank's advertised rate to convert money, so use this factor to load the conversion
    	//e.g. '1' means no adjustment, '1.02' adds 2% to the calculation, '1.1' adds 10% 
    	$adjuster = 1.02;
    
    	//path and filename of local file holding the rates
    	$ratesfile = '/tmp/rateslist.php';
    
    /*
    	--------------------------------
    	NO CONFIGURATION NECESSARY BELOW
    	--------------------------------
    */
    
    	//Load source file
    	$sourcedata = @file_get_contents($sourceurl);
    
    	//parse remote xml file, if currency is on our list write currency code,label, and raw exchange rate (based on Euro) into array
    	$rates_array = array();
    	$p = xml_parser_create();
    	xml_parse_into_struct($p, $sourcedata, $vals, $index);
    	xml_parser_free($p);
    	$rates_array['EUR'] = array(
    		'label' => '',
    		'rate' => 1
    	);
    	foreach ($vals as $k => $v) 
    	{
    		if (array_key_exists('attributes', $v))
    		{ 
    			if(array_key_exists($v['attributes']['CURRENCY'], $currencies))
    			{
    				$curcode = $v['attributes']['CURRENCY'];
    				$curlabel = $currencies[$curcode];
    				$currate = $v['attributes']['RATE'];
    				$rates_array[$curcode] = array(
    					'label' => $curlabel,
    					'rate' => $currate
    				);
    			}
    		}
    	}
    
    	// get a factor to rework all the rates based on our base currency, not on Euro
    	$factor = $rates_array[$base_currency]['rate'];
    
    	// modify the rates based on the base currency
    	foreach(array_keys($rates_array) as $k)
    	{
    		$rates_array[$k]['rate'] = ($rates_array[$k]['rate'] / $factor) * $adjuster;
    	}
    
    	//write currency code, label and exchange rate into local file
    	$fp=fopen($ratesfile,"w"); 
    	foreach ($rates_array as $k => $v)
    	{
    		fputs($fp, "{$k}:{$v['label']}:{$v['rate']}\n");
    	}
    	fclose($fp);
    ?>
    Attached Files Attached Files

  6. #6
    is_empty(2); foofoonet's Avatar
    Join Date
    Mar 2006
    Posts
    1,000
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thats sweet, Chap5, 'specially after a day like to today where there was big moves on the UKPound vs the USDollar.

    You'd want to do that every couple of hours if you are doing a lot of biz.

    Off Topic:

    Hear that? USD, yo 'goin dooooown.

  7. #7
    SitePoint Member
    Join Date
    Jan 2006
    Posts
    5
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You're right, Foofoonet, you've got to be careful with this automated currency conversion. Most sources (including the European Central Bank) only update once daily. You need to say very clearly on your site that actual prices are in your base currency, and that those prices shown in other currencies are for guidance only.

    BTW, the forum posting screen converts html entities (e.g. for Dollar sign), so better to use the attachment than to copy from screen.

    Kevin
    www.kenthouse.com

  8. #8
    SitePoint Wizard
    Join Date
    Jun 2005
    Posts
    1,428
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Thumbs up

    Quote Originally Posted by Chap5
    Here's a fuller version using text file instead of database. This version also gets its data via xml from the European Central Bank - probably a more robust approach than scraping html from Yahoo.

    Code lacks any kind of error trapping - recommend you add some.

    Save the code below as [path]/converter.php


    Enjoy.

    Kevin
    www.kenthouse.com


    Hi Kevin,

    Many thanks for that - it is very much appreciated.

    I've never heard of error trapping before - how do I do that please ?

    Dez.

  9. #9
    SitePoint Member
    Join Date
    Jan 2006
    Posts
    5
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Error trapping

    Many thanks for that - it is very much appreciated.
    No problem, Dez.

    I've never heard of error trapping before - how do I do that please ?
    Ah, well, how long have you got? The basic script supplied works fine if evrything happens as expected. But what if the xml script can't be reached at update time? Or if one of the currencies you have selected can't be found in the xml? You could find that the system is serving out-of-date exchange rates because updating has failed, or worse, some or all of the currencies aren't set at all or are set at a zero rate causing wrong information to appear on your site.

    To catch such possibilities, the code should really be tightened up to alert you if something unexpected has happened and to minimise the consequences of such problems. For instance, the local textfile holding the rates should only be overwitten if the new data has validated (i.e. each of your selected currencies has been found in the remote xml file and a rate picked up that is within a reasonable range). That needs some extra coding. You could also set cron to email you the output from the job every day so that - if you check the email carefully - you will see if anything has gone obviously wrong. Sorry I don't have time to add those refinements right now - somebody else here may be willing and able to oblige, or you might be able to check out tips on php/mysql error trapping within Sitepoint or via Google search and apply the techniques yourself.

    Best wishes

    Kevin
    www.kenthouse.com

  10. #10
    SitePoint Wizard
    Join Date
    Jun 2005
    Posts
    1,428
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Your time is very much appreciated Kevin. I will try the searches and if anyone can lend a further hand on the error trapping - that would be brilliant.

    I tried to work on this straight away, but couldn't open that file you kindly supplied ?

    Any help always appreciated.

    Dez.

  11. #11
    SitePoint Wizard
    Join Date
    Jun 2005
    Posts
    1,428
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Kevin,

    The help you've given on this, has been really appreciated and I thought I would just give an update. I've been trying all sorts of things over the last 2 months and got in a really big mess ;-( so I thought I would just start from fresh again. I did download that file you kindly attached, but not sure where I would put it ;-(

    Ok, on the page below, where would the first step be please ?

    http://www.130605.com/currency

    My hosts don't support asp, but do support php, there's no involvement with any databases and would only need to automatically update every 12 hours.

    Any help much appreciated.

    Dez.

  12. #12
    ✯✯✯ silver trophybronze trophy php_daemon's Avatar
    Join Date
    Mar 2006
    Posts
    5,284
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    If you could post that script running at http://www.130605.com/currency, probably index.php, we could try to guide you.
    Saul

  13. #13
    SitePoint Wizard
    Join Date
    Jun 2005
    Posts
    1,428
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Many thanks - here goes :

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>

    <head>
    <meta http-equiv="Content-Language" content="en-gb">
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <title>Currency</title>
    </head>

    <body bgcolor="#FFFFFF">
    <br>
    <table cellpadding="0" cellspacing="0" width="528">
    <tr>
    <td>The current price, in euros, on the right :&nbsp; 11,493<br>
    <br>
    The equivalent price, in US dollars, automatically appearing to the right:&nbsp; <br>
    <br>
    The equivalent price, in UK pounds, automatically appearing to the right:&nbsp; <br>
    &nbsp;</td>
    </tr>
    </table>

    </body>

    </html>

  14. #14
    SitePoint Enthusiast
    Join Date
    Jul 2006
    Posts
    47
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Why not update in real-time? If you can find a good real-time currency webpage it would be piece of cake to "borrow" the exchange rates in real-time (will slow down your page a bit). You could then write the contents to a text-file and then retrieve the contents of that text-file on the next page load in case the currency webpage is down or doesn't return anything. If you direct me to a good currency webpage I can put something together for you, if you're interested in this approach...
    Sincerely,
    Joe Belmaati
    Copenhagen Denmark

  15. #15
    ✯✯✯ silver trophybronze trophy php_daemon's Avatar
    Join Date
    Mar 2006
    Posts
    5,284
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    I've put it all together:

    1. I've modified converter.php. First of all I took took out configuration block to config.php as it's needed everywhere the conversion is used. Secondly, I've modified docurconversion() so it's more flexible to use.

    2. I've uploaded converter.php and config.php to my public_html. I've created rateslist.php (in public_html) and set it's permissions to 0777.

    3. I've edited index.php to do the conversion.

    I attached all of the files, too much to post here.

    Note that you need to run converter.php before you can use the conversion. You should set up the cron job to run it daily.

    Hope this helps.
    Attached Files Attached Files
    Saul

  16. #16
    ✯✯✯ silver trophybronze trophy php_daemon's Avatar
    Join Date
    Mar 2006
    Posts
    5,284
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Joe Belmaati
    Why not update in real-time? If you can find a good real-time currency webpage it would be piece of cake to "borrow" the exchange rates in real-time (will slow down your page a bit). You could then write the contents to a text-file and then retrieve the contents of that text-file on the next page load in case the currency webpage is down or doesn't return anything. If you direct me to a good currency webpage I can put something together for you, if you're interested in this approach...
    I'm sorry to say this, but that's not a good idea. You don't wanna make your site's speed to rely on a load time of another server or it's availability.
    Saul

  17. #17
    SitePoint Wizard
    Join Date
    Jun 2005
    Posts
    1,428
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by php_daemon
    I've put it all together:

    1. I've modified converter.php. First of all I took took out configuration block to config.php as it's needed everywhere the conversion is used. Secondly, I've modified docurconversion() so it's more flexible to use.

    2. I've uploaded converter.php and config.php to my public_html. I've created rateslist.php (in public_html) and set it's permissions to 0777.

    3. I've edited index.php to do the conversion.

    I attached all of the files, too much to post here.

    Note that you need to run converter.php before you can use the conversion. You should set up the cron job to run it daily.

    Hope this helps.

    Many thanks php daemon - not too sure where to start as it's all very new to me, but as soon as the attachment that you kindly sent in has been approved, I'll download it and try my hardest to fathom it all out.

    Thanks again.

    Dez.

  18. #18
    SitePoint Wizard
    Join Date
    Jun 2005
    Posts
    1,428
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by php_daemon
    I've put it all together:

    1. I've modified converter.php. First of all I took took out configuration block to config.php as it's needed everywhere the conversion is used. Secondly, I've modified docurconversion() so it's more flexible to use.

    2. I've uploaded converter.php and config.php to my public_html. I've created rateslist.php (in public_html) and set it's permissions to 0777.

    3. I've edited index.php to do the conversion.

    I attached all of the files, too much to post here.

    Note that you need to run converter.php before you can use the conversion. You should set up the cron job to run it daily.

    Hope this helps.

    Many thanks for the help on this and for the 4 files php_daemon - it's very much appreciated.

    I've uploaded the 4 files and the index page below has now been replaced with your one.

    http://www.130605.com/currency

    Couple of things - I couldn't see any code or other text in the rateslist.php - was that ok ? Also, how do I do the following things please ? "Note that you need to run converter.php before you can use the conversion. You should set up the cron job to run it daily."

    All the best.

    Dez.

  19. #19
    ✯✯✯ silver trophybronze trophy php_daemon's Avatar
    Join Date
    Mar 2006
    Posts
    5,284
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    You did not set permissions for rateslist.php. You can do that in your cpanel using file manager. Set the permissions to 0777. Or if you use FTP client, type chmod 0777 rateslist.php in the command line.

    You can run converter.php manually, just point your browser to http://www.130605.com/currency/converter.php. You'll see a blank page, but it'll update reateslist.php(be sure to set the permissions first). Of course you do not want to run it manually every day, so you can set up a corn job in your cpanel too. Enter this command in Cron manager in cpanel: /usr/local/bin/php /home/mine/public_html/currency/converter.php and set it to run every day(or whatever you think is fine).
    Saul

  20. #20
    SitePoint Wizard
    Join Date
    Jun 2005
    Posts
    1,428
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Many thanks again php_daemon - it's really appreciated.

    You know what, when you started referring to cron jobs and permissions, it was like another language to me ;-( But, when I looked in my cpanel, there it all was ;-) I had often seen the option for cron jobs and wondered what it was for - now I know ;-)

    I set the permissions for 777 as there was only 3 collumns - I assume this is ok ?

    Now, the page is updating, but in your path in the cron job, there is a slight gap - was that meant ? Also, the figures are not crunching in line with currency rates - the equivalent rate on the example page, in us dollars should be something in the region of 14,658 us dollars !

    All the best.

    Dez.

  21. #21
    ✯✯✯ silver trophybronze trophy php_daemon's Avatar
    Join Date
    Mar 2006
    Posts
    5,284
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    The gap... you mean the space after /usr/local/bin/php? Yes, it's meant to be there. The first part is the path to php compiler, the second is the path to your script to run.

    Yes the conversion is wrong, it's because the base currency is set to GBP. It converts from GBP. In config.php you'll find $base_currency, set it to EUR. Also note that there's an adjustment factor in this script, you may want to alter it in config.php too.
    Saul

  22. #22
    SitePoint Wizard
    Join Date
    Jun 2005
    Posts
    1,428
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Thumbs up

    Many thanks php_daemon - the light at the end of the tunnel is almost here

    Just one last thing - how do you round up or down to the nearest dollar or pound please ? You probably know what I mean, but something like :

    14,637.48 would become 14,637

    14,637.52 would become 14,638

    All the best.

    Dez.
    Last edited by Dez; Jul 12, 2006 at 02:33.

  23. #23
    dooby dooby doo silver trophybronze trophy
    spikeZ's Avatar
    Join Date
    Aug 2004
    Location
    Manchester UK
    Posts
    13,804
    Mentioned
    157 Post(s)
    Tagged
    3 Thread(s)
    Some fine work from php_daemon in this thread

    Dez, have a look at
    round
    ceil
    number_format

    They should help

    Spike
    Mike Swiffin - Community Team Advisor
    Only a woman can read between the lines of a one word answer.....

  24. #24
    SitePoint Wizard
    Join Date
    Jun 2005
    Posts
    1,428
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Thumbs up

    Many thanks for the links Spike and yes, php_daemon has been a great help and really appreciated. ( Not sure where Kevin went to ? )

    Reading through the codes on the links, it's not clear where to put the codes so that it rounds up or down - can anyone lend a hand please ?

    Any help appreciated.

    Dez.

  25. #25
    dooby dooby doo silver trophybronze trophy
    spikeZ's Avatar
    Join Date
    Aug 2004
    Location
    Manchester UK
    Posts
    13,804
    Mentioned
    157 Post(s)
    Tagged
    3 Thread(s)
    for your particular example, round the numbers up or down when you display them:
    PHP Code:
    $number '14,637.48';
    echo 
    round($number);
    // will give 14,637 
    HTH
    Mike Swiffin - Community Team Advisor
    Only a woman can read between the lines of a one word answer.....


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •