多次向下钻取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.

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.

You can do it like this:

 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");

hope that helps.