php解析汇率反馈XML

时间:2012-04-23 13:49:16

标签: php xml parsing

我正在尝试使用欧洲中央银行(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&euro;='.$rate["rate"].' '.$rate["currency"].'<br/>';
        //--------------------------------------------------
        //Here you can add your code for inserting
        //$rate["rate"] and $rate["currency"] into your database
        //--------------------------------------------------
    }
?> 

更新

由于我在我的测试环境中支持代理,我试过这个但仍然无法阅读XML:     function 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

请帮帮我。谢谢!

2 个答案:

答案 0 :(得分:2)

我在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/>';
}

答案 1 :(得分:0)

这个解决方案对我有用:

$data = [];

$url = "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml";
$xmlRaw = file_get_contents($url);

$doc = new DOMDocument();
$doc->preserveWhiteSpace = FALSE;

$doc->loadXML($xmlRaw);

$node1 = $doc->getElementsByTagName('Cube')->item(0);
foreach ($node1->childNodes as $node2) {
    $value = [];

    foreach ($node2->childNodes as $node3) {
        $value['date'] = $node2->getAttribute('time');
        $value['currency'] = $node3->getAttribute('currency');
        $value['rate'] = $node3->getAttribute('rate');

        $data[] = $value;
        unset($value);
    }
}

echo "<pre"> . print_r($data) . "</pre>";