1

我无法理解使用 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
}
?>

我如何找出数组中有多少“人”并用数字标识它们?

4

1 回答 1

0

要计算使用人数:

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;
}
于 2013-02-11T21:15:31.497 回答