我使用SimpleXML并希望获得每个不同的learner
及其子rater
属性,如何将其解析为以下个体:
Learner: John
Rater_1_name: John
Rater_1_email: john@domain.com
Rater_1_group: Self
Rater_2_name: Jane
Rater_2_email: jane@domain.com
Rater_2_group: Manager
Rater_3_name: Nathan
Rater_3_email: nathan@domain.com
Rater_3_group: Peers
// and so on...
要解析的代码:
$xml = '
<users>
<learner name="John">
<rater name="John" email="john@domain.com" group="Self"></rater>
<rater name="Jane" email="jane@domain.com" group="Manager"></rater>
<rater name="Nathan" email="nathan@domain.com" group="Peers"></rater>
</learner>
<learner name="Jane">
<rater name="Jane" email="jane@domain.com" group="Self"></rater>
<rater name="John" email="john@domain.com" group="Peers"></rater>
<rater name="Nathan" email="nathan@domain.com" group="Others"></rater>
</learner>
</users>
';
$sxe = new SimpleXMLElement($xml);
echo $sxe->asXML();
感谢。
答案 0 :(得分:0)
您可以在foreach()循环中访问元素,因为SimpleXMLElement实现了Traversable接口。所以沿着这些方向的事情应该让你开始: -
$xml = '
<users>
<learner name="John">
<rater name="John" email="john@domain.com" group="Self"></rater>
<rater name="Jane" email="jane@domain.com" group="Manager"></rater>
<rater name="Nathan" email="nathan@domain.com" group="Peers"></rater>
</learner>
<learner name="Jane">
<rater name="Jane" email="jane@domain.com" group="Self"></rater>
<rater name="John" email="john@domain.com" group="Peers"></rater>
<rater name="Nathan" email="nathan@domain.com" group="Others"></rater>
</learner>
</users>
';
$sxe = simplexml_load_string($xml);
foreach($sxe as $learner){
$attr = $learner->attributes();
$name = $attr['name'];
echo "Learner $name <br/>Rated by:-<br/>\n";
foreach($learner->rater as $rater){
foreach($rater->attributes() as $key => $value){
echo " - $key = $value <br/>\n";
}
}
}
<强>输出: - 强>
Learner John
Rated by:-
- name = John
- email = john@domain.com
- group = Self
- name = Jane
- email = jane@domain.com
- group = Manager
- name = Nathan
- email = nathan@domain.com
- group = Peers
Learner Jane
Rated by:-
- name = Jane
- email = jane@domain.com
- group = Self
- name = John
- email = john@domain.com
- group = Peers
- name = Nathan
- email = nathan@domain.com
- group = Others