2015-01-13 35 views
1

我找不到官方文檔的解決方案,所以這裏是我的方案:PHP:解析來自立方XML格式的數據

我需要解析數據移出此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的東西否則,我不知道如何申報!可能是隻有一個sintax問題...

UPDATE

我幾乎沒有:這裏

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()。如果我使用單個索引而不是變量(例如01),它將起作用。所以現在的問題是如何動態增加索引! :(

+0

怎麼樣使用XSLT查詢 – philipp

+0

@philipp我從來沒有使用這種方法,你可以請一個實際的例子?我讀過這裏[(w3schools.com)](http://www.w3schools.com/xpath/xpath_syntax.asp),但它不是很清楚我如何將它應用到這種情況下 – Mariano

+1

' //多維數據集/多維數據集/多維數據集或多維數據集[@currency和@rate]'返回所有''您想要的元素的列表......要在簡單的xml上運行查詢,您應該看看這裏:http: //php.net/manual/de/simplexmlelement.xpath.php – philipp

回答

1

嗯,有使用的命名空間的小動作,但是這是代碼:

<?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> 
+0

謝謝,你的代碼工作...不,我只「必須」瞭解如何構建數組... – Mariano