我创建其中很多内容是通过RSS生成一个动态的网站从themoneyconvert.com
网站实时显示货币供稿利率像这样:
希望你得到我DIS思想内容,在3列模板中播放。
供稿网址对themoneyconverter.com都在,我已经叫cityConfig.php
饲料的URL都存储在$currencySource
阵列中的脚本设置。我在每个网址的末尾添加了一个参数。例如,数组中的第一项已添加到现有提要的末尾?x=15
。该参数对应于来自供稿网址的<item>
XML标签的位置。
该标签由下面的代码行访问,该代码位于函数内部,当我找到它时将显示该函数。
$currency['rate'] = $xml->channel->item[$x]->description;
请注意$x
变量高于此变量我将参数传递到。
以下功能位于我的getCurrencyRate.php
脚本中。
<?php
// Get XML data from source
// Check feed exists
function get_currency_xml($currencySource) {
if (isset($currencySource)) {
$feed = $currencySource;
} else {
echo 'Feed not found. Check URL';
}
if (!$feed) {
echo('Feed not found');
}
return $feed;
}
function get_currency_rate($feed) {
$xml = new SimpleXmlElement($feed);
$rate = get_rate($xml, 15); //EUR 15
if ($feed == 'http://themoneyconverter.com/rss-feed/USD/rss.xml?x=16') {
$rate = get_rate($xml, 16); //GBP 16
} else {
$rate = get_rate($xml, 56); //USD 56
}
}
注意上面,我已硬编码的值15, 16 and 56
从这个输出可以在第一图像中在所述柱的顶部观看。我正在尝试从cityConfig.php
脚本中显示的参数集中获取这些值。
上面的get_rate
函数调用如下:
// Get and return currency rate
// Perform regular expression to extract numeric data
// Split title string to extract currency title
function get_rate(SimpleXMLElement $xml, $x) {
$x = (int)$x;
$currency['rate'] = $xml->channel->item[$x]->description;
preg_match('/([0-9]+\.[0-9]+)/', $currency['rate'], $matches);
$rate = $matches[0];
$title['rate'] = $xml->channel->item[$x]->title;
$title = explode('/', $title['rate']);
$title = $title[0];
echo $rate . ' ' . $title . '<br />';
}
为了实现我的目标我已经通过添加以下代码行和更换数值变量$x
改变了get_currency_rate
功能上面。
$vars = parse_url($feed, PHP_URL_QUERY);
parse_str($vars);
和改性功能:
function get_currency_rate($feed) {
$xml = new SimpleXmlElement($feed);
$vars = parse_url($feed, PHP_URL_QUERY);
parse_str($vars);
$rate = get_rate($xml, $x); //EUR 15
if ($feed == 'http://themoneyconverter.com/rss-feed/USD/rss.xml?x=16') {
$rate = get_rate($xml, $x); //GBP 16
} else {
$rate = get_rate($xml, $x); //USD 56
}
}
从上述显示器的输出:
我期待在列中的相同的输出之前,但这个人是不同。任何想法,我错了?
在此先感谢
伟大的答案。 switch语句很有意义。谢谢! – keenProgrammer 2012-02-06 11:21:10