dongshiru5913 2015-11-08 08:44
浏览 51
已采纳

如何从http://www.newyorkfed.org/xml/data/fx/ATSNoon.xml解析此XML文件

I have the following xml file http://www.newyorkfed.org/xml/data/fx/ATSNoon.xml and I have to parse it using PHP. In fact I need to parse all the and to an array. The array I need will be something like:

$rates = (array('date' => '1994-01-06', 'value' => '12.2430'), 
      array('date' => '1994-01-07', 'value' => '13.2430'),
      array(...)
);

Having a poor experience with parsing XML files, I can't succeed with this task no matter what I tried. May I ask for some help guys? Thank you

  • 写回答

2条回答 默认 最新

  • dragonhong641016 2015-11-09 08:07
    关注

    If you register a prefix for the namespace of the elements you can fetch them with Xpath:

    $document = new DOMDocument();
    $document->load($xmlFile);
    $xpath = new DOMXpath($document);
    $xpath->registerNamespace('f', 'http://www.newyorkfed.org/xml/schemas/FX/utility');
    
    $result =[];
    foreach ($xpath->evaluate('//f:Obs') as $obs) {
      $result[] = [
        'date' => $xpath->evaluate('string(f:TIME_PERIOD)', $obs),
        'value' => $xpath->evaluate('string(f:OBS_VALUE)', $obs)
      ]; 
    }
    var_dump($result);
    

    Output:

    array(??) {
      [0]=>
      array(2) {
        ["date"]=>
        string(10) "1994-01-06"
        ["value"]=>
        string(7) "12.2430"
      }
      [1]=>
      array(2) {
        ["date"]=>
        string(10) "1994-01-07"
        ["value"]=>
        string(7) "12.2190"
      }
      [2]=>
      array(2) {
        ["date"]=>
        string(10) "1994-01-10"
        ["value"]=>
        string(7) "12.20
      ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题