I have created a website that contains that uses XML to drive some of its contents, for example, the current exchange rates as shown below.
The website compares three exchange rates and I currently use a separate functions for each city that perform identical goals e.g. returning the current exchange rates.
The only difference between these functions are the positions of the item tag from the XML document that I request the data from.
$exchange['rate'] = $xml->channel->item[15]->description;
Notice item[15] in the above array which provides access to the Euro currency. In the following, the USA currency is item[56] as below.
$exchange['rate'] = $xml->channel->item[56]->description;
Any ideas if it is possible to combine the three functions into a single one to increase cohesion?
The function I use for accessing the Euro currency is:
<?php
function get_rate1(SimpleXMLElement $xml) {
// Match numeric values before and after decimal place
$exchange['rate'] = $xml->channel->item[15]->description;
preg_match('/([0-9]+\.[0-9]+)/', $exchange['rate'], $matches);
$rate = $matches[0];
// Get currency type from title
$title['rate'] = $xml->channel->item[15]->title;
$title = explode('/', $title['rate']);
$title = $title[0];
echo $rate . ' ' . $title . '<br />';
return $rate;
}
?>
The feed URL's are set in another configuration script called cityConfig.php
<?php
// City 1 //
$city1 = 'Paris';
$exchangeRate1 = '1 Euro';
$exchangeRate1RssUrl = 'http://themoneyconverter.com/rss-feed/EUR/rss.xml';
?>
Thanks in advance
How about you change the rate function to this:
<?php
function get_rate(SimpleXMLElement $xml, $id) {
// Match numeric values before and after decimal place
$exchange['rate'] = $xml->channel->item[$id]->description;
preg_match('/([0-9]+\.[0-9]+)/', $exchange['rate'], $matches);
$rate = $matches[0];
// Get currency type from title
$title['rate'] = $xml->channel->item[$id]->title;
$title = explode('/', $title['rate']);
$title = $title[0];
echo $rate . ' ' . $title . '<br />';
return $rate;
}
?>
Then you can call it like this instead:
$rate1 = get_rate($xml,15);
$rate2 = get_rate($xml,56);