背景:
我创建了一个动态网站,其中许多内容是由themoneyconvert.com的 RSS 提要生成的
该网站显示实时汇率,如下所示:
希望您了解我在 3 列模板中显示的内容。
themoneyconverter.com的提要 URL是在我调用的脚本中设置的cityConfig.php
<?php
// Feed URL's //
$theMoneyConverter = 'http://themoneyconverter.com/rss-feed/';
// Define arrays //
$cities = array('London', 'New York', 'Paris');
$currencySource = array($theMoneyConverter . 'GBP/rss.xml?x=15', $theMoneyConverter . 'USD/rss.xml?x=16', $theMoneyConverter . 'EUR/rss.xml?x=56');
?>
提要 URL 存储在$currencySource
数组中。我在每个 URL 的末尾添加了一个参数。例如,数组中的第一项已?x=15
添加到现有提要的末尾。此参数对应于<item>
提要 URL 中 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 />';
}
为了实现我的目标,我get_currency_rate
通过添加以下代码行并将数值替换为 variable 来更改上面的函数$x
。
$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
}
}
上面的输出显示:
我期望列中的输出与以前相同,但这个不同。有什么想法我哪里出错了吗?
提前致谢