php parse exchange rate feed XML

2019-03-03 10:38发布

I am trying to use the currentcy exchange rate feeds of the European Central Bank (ECB) http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml

They have provided documentation on how to parse the xml but none of the options works for me: I checked that allow_url_fopen=On is set.

http://www.ecb.int/stats/exchange/eurofxref/html/index.en.html

For instance, I used but it doesn't echo anything and it seems the $XML object is always empty.

<?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
        //--------------------------------------------------
    }
?> 

Update:

As I am behind proxy at my test environment, I tried this but still I don't get to read the 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

Please help me. Thanks!

标签: php xml parsing
1条回答
看我几分像从前
2楼-- · 2019-03-03 11:16

I didn't find any relevant settings in php.ini. Check with phpinfo() if you have SimpleXML support and cURLsupport enabled. (You should have them both and especially SimpleXML since you're using it and it returns false, it doesn't complain about missing function.)

Proxy might be an issue here. See this and this answer. Using cURL could be an answer to your problem.


Here's one alternative 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/>';
}
查看更多
登录 后发表回答