我正在尝试使用欧洲中央银行 (ECB) 的当前汇率源 http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml
他们提供了有关如何解析 xml 的文档,但没有一个选项对我有用:我检查了 allowed_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);
返回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
中没有找到任何相关设置。检查 phpinfo()
是否启用了 SimpleXML
支持和 cURLsupport
。 (您应该同时拥有它们,尤其是 SimpleXML
,因为您正在使用它并且它返回 false,它不会提示缺少功能。)
代理可能是一个问题。请参阅this和 this回答。使用cURL可能是您问题的答案。
这是找到的一种替代方案 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€='.$rate["rate"].' '.$rate["currency"].'<br/>';
}
关于php解析汇率提要XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10281849/