2012-01-16 1 views
1

私は次のようなXMLから、SimpleXMLは要素を持っている:ループ

そうのように、私のワイルドカードとそれらをループするにはどうすればよい
<Result> 
    <BlueAnswer>Blue</BlueAnswer> 
    <RedAnswer>Red</RedAnswer> 
    <YellowAnswer>Yellow</YellowAnswer> 

    <BlueQuestion>What is my favorite color?</BlueQuestion> 
    <RedQuestion>What is my favorite color?</RedQuestion> 
    <YellowQuestion>What is my favorite color?</YellowQuestion> 
</Result> 

foreach ($response->Result->wildcard('*Answer') as $answer) { 
    echo "Answer: " . $answer; 
} 

このシンプルなようですが、私はそれを把握していないようです。事前に助けてくれてありがとう。

+0

あなたはおそらく探していると、[Xpathの](http://www.php.net/manual/en/simplexmlelement.xpath.php)である - しかし、できないあなただけのループ '$対応 - >結果 '? – DaveRandom

+0

'$ response-> Result'に他の子要素があるので、それより複雑です。私は私の質問を更新しました。 – element119

+0

[ノード名のXPathワイルドカード]の重複が可能です(http://stackoverflow.com/questions/4203119/xpath-wildcards-on-node-name) – Wrikken

答えて

2
foreach($response->xpath("/Result/*[substring(name(),string-length(name()) - 5) = 'Answer']") as $answer){ 
    echo $answer; 
} 
+0

私のために働いていないようです。上記のコードに誤りがありますか? – element119

+0

ここで動作しますが、 'Result'がルートノードでない場合は、適切なパスを適宜追加してください(あるいは、' - > xpath( "* * [substring ....')で始まります。 – Wrikken

+0

)例えば、 'Result'はルートノードではないので、' $ response-> Result-> xpath( "// * [substring ...]')は動作しますか? – element119