Hi Guys
I'm back...greetings to all and thanks for keeping in touch.
Not sure even where to post this question but php section usually is cool.
Is there any guru here willing to help me make a display of exchange rates on my site? I only need Euro, Sterling, USD and BG lev.
Regards
F

Dani AI

Generated

Short summary and recommended approach: pick a maintained API (JSON) for rates, fetch server‑side on a schedule, cache/store the results in your database, and serve the stored values to pages. Scraping HTML (the curl/preg approach mentioned by ) works short‑term but is brittle and often violates service terms — a JSON API is simpler and more robust for production. (exchangerate.host)

Practical example (minimal): fetch a JSON endpoint and update a currency table with PDO and prepared statements. The snippet below shows the core idea (replace credentials and table/column names as needed):

<?php
$json = file_get_contents('https://api.exchangerate.host/latest?base=EUR&symbols=USD,GBP,BGN');
$data = json_decode($json, true);
$rates = $data['rates'];

$pdo = new PDO('mysql:host=localhost;dbname=yourdb;charset=utf8mb4',$dbUser,$dbPass,
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);

$stmt = $pdo->prepare('UPDATE currency SET rate = :rate, updated_at = NOW() WHERE code = :code');
foreach ($rates as $code => $rate) {
    $stmt->execute([':rate' => $rate, ':code' => $code]);
}
?>

Using prepared statements prevents the quoting/SQL errors seen in ’s update loop and stops SQL injection; see PDO prepared‑statement guidance. (php.net)

Why this fixes your original problems: the old code used POSIX ereg and the legacy mysql_* API (both deprecated/removed in current PHP versions), and the update SQL omitted quotes around the currency code so the DB saw an invalid identifier. Move to JSON or parse XML with SimpleXML if you must, and switch to PDO or mysqli + prepared statements. The PHP migration notes and RFCs explain these removals and why modern APIs are safer. (php.net)

Deployment tips: run the fetch in a cron job (cache results, store a timestamp), use DECIMAL for rate columns (e.g. DECIMAL(18,8)) to keep precision, check API rate limits / terms before production, and log failures so you can fall back to the last cached rates when the API is unavailable. (exchangerate.host)

Recommended Answers

All 8 Replies

Welcome back (I don't know you though). Could you explain what exactly are you looking for ?

I would suggest using curl to tap into another websites currency converter. Let me know if you would like an example as it would be kinda hard to make.

I would suggest using curl to tap into another websites currency converter. Let me know if you would like an example as it would be kinda hard to make.

I would surely love to see one..

Hi Guys
I'm back...greetings to all and thanks for keeping in touch.
Not sure even where to post this question but php section usually is cool.
Is there any guru here willing to help me make a display of exchange rates on my site? I only need Euro, Sterling, USD and BG lev.
Regards
F

Hi
So far I have this

<?php
//This is a PHP (4/5) script example on how eurofxref-daily.xml can be parsed 

//Read eurofxref-daily.xml file in memory 
$XMLContent= file("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
//the file is updated daily between 14:15 and 15:00 CET

foreach ($XMLContent as $line) {
        if (ereg("currency='([[:alpha:]]+)'",$line,$currencyCode)) {
            if (ereg("rate='([[:graph:]]+)'",$line,$rate)) {
                    //Output the value of 1 EUR for a currency code 
                    echo '1 &euro; = '.$rate[1].' '.$currencyCode[1].'<br />';
                    //--------------------------------------------------
                    // Here you can add your code for inserting
                    // $rate[1] and $currencyCode[1] into your database
                    //--------------------------------------------------
            }
        }
}
?>

but want to make it much better. I guess could now throw into a database and extract whatever is required, even to make one of those on-line calculators.
Best
F

Hi again
here is the code that I have so far but can't get it insert data into my database. Any help would be appreciated.
best
F

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>

<?php
require("./resources/globals.php");	
//This is a PHP (4/5) script example on how eurofxref-daily.xml can be parsed 

//Read eurofxref-daily.xml file in memory 
$XMLContent= file("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
//the file is updated daily between 14:15 and 15:00 CET

foreach ($XMLContent as $line) {
        if (ereg("currency='([[:alpha:]]+)'",$line,$currencyCode)) {
            if (ereg("rate='([[:graph:]]+)'",$line,$rate)) {
                    //Output the value of 1 EUR for a currency code 
                    echo '1 &euro; = '.$rate[1].' '.$currencyCode[1].'<br />';
					
	$rate=$rate[1];
	$currencyCode=$currencyCode[1];
	$updateStmt = "Update currency SET rate=$rate  WHERE code = $currencyCode ";
	

// Connect to the Database
if (!($link=mysql_pconnect($location,$userName,$password))) {
   DisplayErrMsg(sprintf("error connecting to host %s, by user %s",
                             $location, $userName)) ;
   //exit() ;
}

// Select the Database
if (!mysql_select_db($dbname, $link)) {
   DisplayErrMsg(sprintf("Error in selecting %s database", $dbname)) ;
   DisplayErrMsg(sprintf("error:%d %s", mysql_errno($link), mysql_error($link))) ;
   //exit() ;
}

// Execute the Statement
if (!mysql_query ($updateStmt)){
echo $updateStmt;
// Execute the Statement
//if (!mysql_query($updateStmt, $link)) {
   DisplayErrMsg(sprintf("Error in executing %s stmt", $updateStmt)) ;
   DisplayErrMsg(sprintf("error:%d %s", mysql_errno($link), mysql_error($link))) ;
   //exit() ;
}

}
echo $updateStmt; ///displays only one record and no database insert
			}
		
}

?> 

</body>
</html>

I would surely love to see one..

Well here is a function:

function currency_convert($Amount,$currencyfrom,$currencyto)
{
$buffer=file_get_contents('');
preg_match_all('/name=(\"|\')conversion-date(\"|\') value=(\"|\')(.*)(\"|\')>/i',$buffer,$match);
$date=preg_replace('/name=(\"|\')conversion-date(\"|\') value=(\"|\')(.*)(\"|\')>/i','$4',$match[0][0]);
unset($buffer);
unset($match);
$buffer=file_get_contents(''.$date.'/'.$Amount.'-'.strtolower($currencyfrom).'-to-'.strtolower($currencyto).'.html');
preg_match_all('/<span class=\"converted-result\">(.*)<\/span>/i',$buffer,$match);
$match[0]=preg_replace('/<span class=\"converted-result\">(.*)<\/span>/i','$1',$match[0]);
//return $buffer;
unset ($buffer);
return $match[0][0];
}
//Theory: currency_convert(Amount,From,To)
echo currency_convert(150.5,'GBP','AUD');

And the possible entries that can be entered into the from and to field are as follows:

-------------
CONVERT FROM:
-------------

British Pound         GBP
Euro                  EUR
US Dollar             USD
Japanese Yen          JPY
Chinese Yuan          CNY
Australian Dollar     AUD
Swiss Franc           CHF
Canadian Dollar       CAD
Thai Baht             THB
Indian Rupee          INR
Indonesian Rupiah     IDR
Hong Kong Dollar      HKD

-----------
CONVERT TO:
-----------

Euro                  EUR
British Pound         GBP
US Dollar             USD
Japanese Yen          JPY
Chinese Yuan          CNY
Australian Dollar     AUD
Swiss Franc           CHF
Canadian Dollar       CAD
Thai Baht             THB
Indian Rupee          INR
Indonesian Rupiah     IDR
Hong Kong Dollar      HKD

As you can see all the names have abbreviations. For this script, you need to use these abbreviations to be able to convert currencies. And in case if you are wondering how it works, it uses the yahoo currency converter which as far as I am aware hasn't clearly stated anying that could cause legal problems with this script. And also note it takes about 3 seconds to process this function.

Cool thanks, I'll have a look see and try to get it to work.
Best
F

This site allows you to add currency exchange rates table to your site. You can add any pair of currencies to the table.

<website snipped>

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.