解析XML结果中的数组
问题描述:
我无法理解使用SimpleXMLElement打印数组结果的正确语法。从我的XML结果中,我必须要求用户将自己与数组中找到的其中一个人进行匹配,但我不确定什么是最好的方式来做到这一点。解析XML结果中的数组
示例XML结果:
[authentication] => SimpleXMLElement Object
(
[age] => SimpleXMLElement Object
(
[code] => 5
[ambiguous] => SimpleXMLElement Object
(
[person] => Array
(
[0] => SimpleXMLElement Object
(
[name] => Paul Foreman
[question] => SimpleXMLElement Object
(
[id] => dcalc3
[prompt] => What+do+the+%3Cb%3Elast+four%3C%2Fb%3E+digits+of+your+Social+Security+Number+add+up+to%3F
[answer] => 5
)
)
[1] => SimpleXMLElement Object
(
[name] => Paul Foreman
[question] => SimpleXMLElement Object
(
[id] => dcalc3
[prompt] => What+do+the+%3Cb%3Elast+four%3C%2Fb%3E+digits+of+your+Social+Security+Number+add+up+to%3F
[answer] => 6
)
)
)
)
)
)
解决方案即时寻找:
<?php
$string = $xml_result;
$xml = new SimpleXMLElement($string);
$is_age_code = $xml->authentication->{'age'}->code;
if($x_is_age_code == '5'){
// code 5 means more than one match found
// Ask user verification question
// If answer matches question
// Set current user as that person
}
?>
我如何找出有多少“人”是在数组中,并与多家识别他们?
答
要计算的人数使用:
echo count($xml->authentication->age->ambiguous->person);
要访问一个人的子节点使用
echo $xml->authentication->age->ambiguous->person[0]->question->prompt;
或一个循环:
foreach ($xml->authentication->age->ambiguous->person as $person) {
echo $person->question->prompt;
}
+0
谢谢你的工作,这帮助我使用循环编写自己的逻辑。 – Hector 2013-02-11 21:34:02
所以给你的示例XML ,你正在寻找的数字是2?因为数组$ xml-> authentication-> age-> ambiguous-> person'中有2个人?然后你可以使用'count($ xml-> authentication-> age-> ambiguous-> person)'。 – migg 2013-02-11 21:01:11
我看到好的谢谢,但我如何回应问题提示? $ xml-> authentication - > {'age'} - > ambiguos - > {'person'} - > question - > {'prompt'} does not work both $ xml-> authentication - > {'age'} - > ambiguos - > {'person'} - > 0 - > {'question'} - > prompt – Hector 2013-02-11 21:08:13
尝试'$ xml-> authentication-> age-> ambiguous-> person [0] - > question-> prompt'。由于'person'是一个数组,你必须将它用作数组而不是对象。 – migg 2013-02-11 21:11:26