我正在尝试使用欧洲中央银行(ECB)的当前汇率提要http://www.ECB.int/stats/eurofxref/eurofxref-daily.xml
他们提供了关于如何解析xml的文档,但没有一个选项对我有效:我检查了是否设置了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€='.$rate["rate"].' '.$rate["currency"].'<br/>';
//--------------------------------------------------
//Here you can add your code for inserting
//$rate["rate"] and $rate["currency"] into your database
//--------------------------------------------------
}
?>
更新:
由于我在测试环境中处于代理之后,我尝试了此操作,但仍然无法读取XML:函数curl($URL){$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
请帮帮我.谢谢!
我在php.ini
中没有找到任何相关设置。如果启用了simplexml
支持和curlsupport
,请使用phpinfo()
进行检查。(您应该同时拥有它们,特别是simplexml
,因为您正在使用它,并且它返回false,所以它不会抱怨缺少函数。)
代理可能是一个问题。看到这个和这个答案。使用cURL可以解决你的问题。
这里有一个可供选择的foud。
$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€='.$rate["rate"].' '.$rate["currency"].'<br/>';
}