2012-04-23 67 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