php解析汇率提要XML

标签 php xml parsing

我正在尝试使用欧洲中央银行 (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&euro;='.$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,它不会提示缺少功能。)

代理可能是一个问题。请参阅thisthis回答。使用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&euro;='.$rate["rate"].' '.$rate["currency"].'<br/>';
}

关于php解析汇率提要XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10281849/

相关文章:

python - 在 Python 中使用 ElementTree 更改命名空间前缀

parsing - 如何使用 PetitParser 解析以关键字开头的标识符?

parsing - 查找语法中的第一个集合

php - 使用 PHP 从 Azure 网站运行 Azure WebJob

PHP 和 MySql 有日期问题...?

php - MySQL 将每个日期字段转换为时间戳

xml - 向位于 XML 架构中多个子元素内的元素添加唯一 id

php - 我用 PHP sqrt 进行的练习不起作用

jquery - 使用 jQuery 解析 XML

parsing - 通过修剪句子来减少斯坦福解析器的解析时间