2012-04-23 102 views
1

我想使用歐洲央行的currentcy匯率飼料 http://www.ecb.int/stats/eurofxref/eurofxref-daily.xmlPHP解析匯率飼料XML

他們對如何解析XML,但沒有一個選項適用於提供的文件(ECB)我:我檢查了allow_url_fopen = On設置。

http://www.ecb.int/stats/exchange/eurofxref/html/index.en.html

舉例來說,我使用,但其並沒有任何迴音,似乎在$ XML對象始終是空的。

<?php 
    //This is aPHP(5)script example on how eurofxref-daily.xml can be parsed 
    //Read eurofxref-daily.xml file in memory 
    //For the next command you will need the config option allow_url_fopen=On (default) 
    $XML=simplexml_load_file("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"); 
    //the file is updated daily between 2.15 p.m. and 3.00 p.m. CET 

    foreach($XML->Cube->Cube->Cube as $rate){ 
     //Output the value of 1EUR for a currency code 
     echo '1&euro;='.$rate["rate"].' '.$rate["currency"].'<br/>'; 
     //-------------------------------------------------- 
     //Here you can add your code for inserting 
     //$rate["rate"] and $rate["currency"] into your database 
     //-------------------------------------------------- 
    } 
?> 

更新:

由於我身後代理在我的測試環境,我試過,但我仍然沒有得到讀取XML: 功能捲曲($網址){$ CH = curl_init(); curl_setopt($ ch,CURLOPT_URL,$ url);
curl_setopt($ ch,CURLOPT_RETURNTRANSFER,1);
curl_close($ ch);
return curl_exec($ ch); }

$address = urlencode($address); 
$data = curl("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml"); 
$XML = simplexml_load_file($data); 

var_dump($XML); -> returns boolean false 

請幫幫我。謝謝!

+0

var_dump($ XML)是什麼意思? – noli 2012-04-23 13:52:09

+0

你有錯誤報告嗎?它是什麼意思?您是否使用PHP5並在'php.ini'中啓用了XML支持?腳本是從我的本地計算機運行的,那麼您的或銀行的網絡問題是否會出現暫時的問題? – 2012-04-23 14:01:21

+0

它適用於我的系統。既然你有'allow_url_fopen = On',嘗試添加'allow_url_include = On'。 – 2012-04-23 14:35:08

回答

2

我沒有在php.ini找到任何相關的設置。如果您有SimpleXML支持和cURLsupport啓用,請與phpinfo()覈對。 (你應該有他們兩個,特別是SimpleXML,因爲你使用它,它返回false,它不會抱怨丟失的功能。)

代理可能是一個問題在這裏。請參閱thisthis的答案。使用cURL可以解決您的問題。


這裏有一個替代foud here

$url = file_get_contents('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'); 
$xml = new SimpleXMLElement($url) ; 

//file put contents - same as fopen, wrote and close 
//need to output "asXML" - simple xml returns an object based upon the raw xml 
file_put_contents(dirname(__FILE__)."/loc.xml", $xml->asXML()); 

foreach($xml->Cube->Cube->Cube as $rate){ 
    echo '1&euro;='.$rate["rate"].' '.$rate["currency"].'<br/>'; 
} 
+0

謝謝。我已經啓用了它。我試過cURL,但是我仍然沒有閱讀XML。我甚至保存了本地副本,並嘗試了$ XML = simplexml_load_file('test.xml');和var_dump($ XML);我仍然布爾錯誤。我不明白。 – Veni 2012-04-24 10:22:37

+0

@Veni找到一個替代解決方法。不知道什麼是這裏的問題,你甚至不能讀取本地文件。你能讀取任何XML文件?你的文件的編碼是否正確(本地文件保存爲utf8文件,它沒有在文件中聲明爲utf8'<?xml version =「1.0」encoding =「UTF-8」?>')?我很困惑... – 2012-04-24 11:18:48

+0

是的,我的本地文件保存爲UTF-8。我不明白。顯然這是我的設置的一些本地問題。任何想法如何解決這個問題?謝謝! – Veni 2012-04-25 06:55:16