正在分析XML结果中的数组


Parsing array within XML result

我很难理解使用SimpleXMLElement打印数组结果的正确语法。根据我的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;
}