douhao5280 2013-02-15 00:17
浏览 42
已采纳

多次向下钻取xml Feed的有效方法

Ive found myself drilling down through xml feeds quite allot, they are almost identical feeds apart from a couple of array names.

Ideally id want to make a sort of function that i can call, but i have no idea how to do it with this sort of data

//DRILLING DOWN TO THE PRICE ATTRIBUTE FOR EACH FEED & MAKING IT A WORKING VAR
  $wh_odds = $wh_xml->response->will->class->type->market->participant;
  $wh_odds_attrib = $wh_odds->attributes();
  $wh_odds_attrib['odds'];


  $lad_odds = $lad_xml->response->lad->class->type->market->participant;
  $lad_odds_attrib = $lad_odds->attributes();
  $lad_odds_attrib['odds'];

as you can see they are essentially the very similar, but im not quite sure how i can streamline the process of setting a working var without writing 3 lines each time.

  • 写回答

2条回答 默认 最新

  • doushang9172 2013-02-15 14:23
    关注

    The function you're probably looking for is called SimpleXMLElement::xpath().

    XPath is a language of it's own designed to pick stuff out of XML files. In your case, the xpath expression to get the odds attribute of all these elements is:

    response/*/class/type/market/participant/@odds
    

    You can also replace the * with the concrete element name or allow multiple names there and what not.

    $odds = $lad_xml->xpath('response/*/class/type/market/participant/@odds');
    

    Different to your code, this has all attribute elements inside the array (you have the attribute's parent element inside the variable). An example outcome (considering two of such elements) would be:

    Array
    (
        [0] => SimpleXMLElement Object
            (
                [@attributes] => Array
                    (
                        [odds] => a
                    )
    
            )
    
        [1] => SimpleXMLElement Object
            (
                [@attributes] => Array
                    (
                        [odds] => a
                    )
    
            )
    
    )
    

    You can turn that into strings as well easily:

    $odds_strings = array_map('strval', $odds);
    
    print_r($odds_strings);
    
    Array
    (
        [0] => a
        [1] => a
    )
    

    Xpath is especially useful if you say, you want to get all participant element's odds attributes:

    //participant/@odds
    

    You don't need to explicitly specify each of the parent element names.

    I hope this is helpful.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备