PHP:从多维数据集XML格式解析数据


PHP: parsing data from Cube XML format

我在官方文档中找不到解决方案,所以这是我的方案:

我需要从这个 xml 中解析数据:http://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml

这是我到目前为止实现的代码:

$xml=simplexml_load_file('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml');
foreach($xml->Cube->Cube as $x) {
    $arr[date('d-m',strtotime($x['time']))] = array();
    foreach($xml->Cube->Cube->Cube as $y) {
        $arr[(string)$y['currency']] = (float)$y['rate'];
    };
};

问题是这段代码显然只会解析第一组费率,而我需要解析为每个日期设置的每个费率,然后我需要用我不知道如何声明的其他东西更改$xml->Cube->Cube->Cube!那可能只是一个罪恶问题...

更新

我快到了:

foreach($xml->Cube->Cube as $x) {
    for ($i=0;$i<90;$i++) {
        foreach($xml->Cube->Cube[$i]->Cube as $y) {
                $arr[date('d-m',strtotime($x['time']))][(string)$y['currency']] = (float)$y['rate'];
        }
    }
}

这里的问题是在第 #3 行:foreach不接受变量$i并返回Invalid argument supplied for foreach() .如果我使用变量的单个索引 istead(例如 01),它将起作用。所以现在的问题是如何动态地递增索引!:(

好吧,使用命名空间有一个小技巧,但这就是代码:

<?php
    $xml  = simplexml_load_file('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml');
    $xml->registerXPathNamespace('d', 'http://www.ecb.int/vocabulary/2002-08-01/eurofxref');
    $list = $xml->xpath('//d:Cube[@currency and @rate]');
?>
<!DOCTYPE html>
<html>
    <head>
        <title>xpath</title>
   </head>
   <body>
       <table>
           <tr>
               <th>id</th>
               <th>currency</th>
               <th>rate</th>
           </tr>
           <?php $count = 0; ?>
           <?php foreach ($list as $cube): ?>
           <?php $attrs = $cube->attributes(); ?>
           <tr>
               <td><?php echo ++$count; ?></td>
               <td><?php echo $attrs['currency']; ?></td>
               <td><?php echo $attrs['rate']; ?></td>
           </tr>
           <?php endforeach; ?>
        </table>
    </body>
</html>