1

xml フィードを掘り下げてみると、いくつかの配列名を除けばほとんど同じフィードです。

理想的には、私が呼び出すことができる一種の関数を作成したいのですが、この種のデータでそれを行う方法がわかりません

//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行を書かずに作業変数を設定するプロセスを合理化する方法がよくわかりません。

4

2 に答える 2

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

それが役立つことを願っています。

于 2013-02-15T00:25:50.863 に答える
1

おそらく探している関数は と呼ばれSimpleXMLElement::xpath()ます。

XPath は、 XML ファイルから内容を選択するために設計された独自の言語です。oddsあなたの場合、これらすべての要素の属性を取得する xpath 式は次のとおりです。

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

*を具体的な要素名に置き換える、そこに複数の名前を許可することもできます。

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

コードとは異なり、これには配列内にすべての属性要素があります (変数内に属性の親要素があります)。結果の例 (そのような要素の 2 つを考慮した場合) は次のようになります。

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
)

participantXpath は、すべての要素のodds属性を取得したい場合に特に便利です。

//participant/@odds

各親要素名を明示的に指定する必要はありません。

これがお役に立てば幸いです。

于 2013-02-15T14:23:31.453 に答える