2012-02-02 42 views
0

我需要一些幫助獲得一個銀行RSS飼料到我的數據庫。我嘗試了一些東西,但我似乎無法讓它工作。獲取一個銀行RSS飼料到我的MySQL數據庫與PHP?

RSS提要是從http://www.bankofcanada.ca/stats/assets/rates_rss/noon/en_all.xml

<?php 

//Find and grab needed libraries and files. 
require_once('proxy_bypass.php'); 
require_once ('config.php'); 

$url = $BOCRSS; // Bank of Canada RSS. 

$rss = @simplexml_load_string(get_file($url)); // Get the rss feed data. 

if($rss) { 
foreach($rss->item as $entry) { //For each RSS item in the rss xml file. 
    $cb = $entry->children('http://www.cbwiki.net/wiki/index.php/Specification_1.1'); 

    //var_dump($cb);   
    //die(); 

    $code = $entry[targetCurrency]; 
    $curr = $entry[value]; 
    //echo $curr .' '. $code . '<br/>'; //Can be deleted - prints out data. 

    $dbc = mysql_connect($db_host,$db_user,$db_password); //Connect to Shares. 
    mysql_select_db($db_name, $dbc); //Select database. 
    $qry = "INSERT INTO $db_table (currencycode,rate) VALUES ('$code', '$curr')"; //Creates the query. 
    if (!$dbc){ 
    die('Could not connect: ' . mysql_error()); // Echo this is the connection to the database can't be made. 

} 

if (mysql_query($qry, $dbc)) { 
    echo "Database created"; // Echo this if the RSS feed in placed in the database. 
} 
else { 
    echo "Error creating database: " . mysql_error(); //Otherwise say this. 
} 
mysql_close($dbc); // Close the database connection. 
} 

} else echo "Error with RSS feed"; //Echo error if RSS is unreachable. 

?> 

我已經包含了這兩個文件獲得通過我的大學的代理服務器和配置持有我的MySQL數據庫的詳細信息和網址RSS源。

的變種轉儲給我此:

對象(的SimpleXMLElement)#63(1){[ 「統計」] =>對象(的SimpleXMLElement)#65(2){[ 「國」] => string(2)「CA」[「exchangeRate」] => object(SimpleXMLElement)#66(5){[「value」] => string(6)「1.0029」[「baseCurrency」] => string(3)「 CAD「[」targetCurrency「] =>字符串(3)」USD「[」rateType「] =>字符串(24)」加拿大銀行中午利率「[」observationPeriod「] =>字符串(25) 01T12:15:00-05:00「}}}

現在我是PHP的初學者,所以它可能都是錯誤的。我試圖讓'targetCurrency'和'value'進入我的數據庫,但我得到的是50多行空行。它必須意味着數據庫正在生成,但沒有任何進展。如果任何人都可以更改代碼以使其正常工作,我將不勝感激,因爲我試圖讓它正常工作,但無濟於事。

+0

**警告**您的代碼易受sql注入攻擊。 – 2012-02-02 14:04:38

回答

0

不應該使用$ cb(每個項目的第一個子節點)而不是$ element?

$code = $cb['targetCurrency']; 
$curr = $cb['value']; 

另外,請使用類似mysql_real_escape_string($rss_field_value)逃脫你把值SQL查詢,以防止SQL注入。

+0

我將舊代碼更改爲「code = $ cb ['targetCurrency']; + $ curr = $ cb ['value'];」。然後,我做了一個變量轉儲以查看發生了什麼。它們都返回NULL。我的空行問題仍然存在。無論如何,你所說的話會留下來,因爲它似乎是一個合乎邏輯的答案。謝謝。 – Zyble 2012-02-02 14:56:43