2013-02-15 31 views
1

我發現自己在xml feed中進行了相當的分配,除了幾個數組名稱之外,它們幾乎完全相同。高效地深入瞭解xml feed多次

理想ID要打排序功能,我可以打電話,但我不知道如何處理這種數據

//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']; 

的做到這一點,你可以看到他們在本質上是非常相似的,但我不太清楚如何簡化設置工作變量的過程,而不必每次寫入3行。

回答

1

您可能要查找的功能稱爲SimpleXMLElement::xpath()

XPath is a language它自己設計從XML文件中挑選出來的東西。在你的情況下,XPath表達式來獲取所有這些元素的odds屬性是:

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

您也可以與具體的元素名稱替換*允許多個名稱有什麼不可以。

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

不同,以你的代碼,這有數組(你有變數內屬性的父元素)內的所有屬性元素。 (考慮到兩個這樣的元素)的一個例子的結果是:

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

     ) 

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

     ) 

) 

你可以把它轉換成字符串以及容易:

$odds_strings = array_map('strval', $odds); 

print_r($odds_strings); 

Array 
(
    [0] => a 
    [1] => a 
) 

XPath是,如果你說是特別有用的,你想獲得的所有participant元素的odds屬性:

//participant/@odds 

你並不需要顯式地指定每個父元素名稱。

我希望這是有幫助的。

1

你可以這樣說:

function getAttrib ($xmlObj, $attrName) { 
     $wh_odds = $xmlObj->response->$attrName->class->type->market->participant; 
     $wh_odds_attrib = $wh_odds->attributes(); 
     return $wh_odds_attrib['odds']; 
} 

getAttrib ($wh_xml, "will"); 

希望幫助。