2013-02-11 78 views
1

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

我如何找出有多少「人」是在數組中,並與多家識別他們?

+0

所以給你的示例XML ,你正在尋找的數字是2?因爲數組$ xml-> authentication-> age-> ambiguous-> person'中有2個人?然後你可以使用'count($ xml-> authentication-> age-> ambiguous-> person)'。 – migg 2013-02-11 21:01:11

+0

我看到好的謝謝,但我如何迴應問題提示? $ 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

+0

嘗試'$ xml-> authentication-> age-> ambiguous-> person [0] - > question-> prompt'。由於'person'是一個數組,你必須將它用作數組而不是對象。 – migg 2013-02-11 21:11:26

回答

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; 
} 
+0

謝謝你的工作,這幫助我使用循環編寫自己的邏輯。 – Hector 2013-02-11 21:34:02