Create your own exchange rate page with scraper

Posted 2 years ago

Whether you’re looking for a test or to build your own exchange rate website, it is pretty straight forward. I’ve popped the code below and commented along the way.


<?php
// Check if the file has been grabbed within the last hour
// if the modified time is greater than 3600 seconds (1 hour)
// grab the file again, if not, use our cached version
if (time()-filemtime("eurofxref-daily.xml") > 3600) {

  $content = file("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml"); // Go to the European bank and grab the latest exchange rates in xml format
  $fh = fopen("eurofxref-daily.xml","w"); // Open the file with write permissions (call this whatever you like, I've kept the same naming convention for ease)
  foreach ($content as $line) { fputs($fh,$line); } // Write the contents to our local file line by line.
  fclose ($fh); // Close the file handler

  echo 'Freshly loaded content'; // Tell the user we have only just grabbed this file (not required)

} else {
  $content = file("eurofxref-daily.xml"); // File has been grabbed within the last hour, use this version
  echo 'Cached within the last hour';
}

// Open our file and loop over each line with a new variable called $lineItem
foreach ($content as $lineItem) {

  // If the row has "currency" followed by some characters AND has a exchange rate, add it ito our newly created data array
  if(preg_match("/currency='([[:alpha:]]+)'/",$lineItem,$a) && preg_match("/rate='([[:graph:]]+)'/",$lineItem,$b)){
    // Each item should be passed into the array as a key value pair, which means
    // if I find the above conditional (preg_match) to be successful, I want to keep these values together
    // so that I can access them later on. The array would look like this
    // [USD] => 1.0980        [KEY] => VALUE
    $data[$a[1]] = $b[1];
  }
}
?>
<html>
<head><title>Exchange rates</title></head>
<body><h1>Today's Exchange Rates from/to Euro</h1>
<?php
// Loop over our data array returning the key (GBP) and the value which happens to be the exchange rate (0.79)
// $k is short for key and likewise, $v for value.
foreach ($data as $k => $v) {
  echo $k . ' - ' . $v . '<br>';
}
?>
</body>
</html>