バックグラウンド:
themoneyconvert.comからの RSS フィードによって多くのコンテンツが生成される動的な Web サイトを作成しました。
ウェブサイトには、次のようなライブ通貨レートが表示されます。
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
}
}
上記の出力は次のように表示されます。
以前と同じ列の出力を期待していますが、これは異なります。私が間違っていたアイデアはありますか?
前もって感謝します