2012-03-19 64 views
0

我被困在試圖訪問我的SimpleXmlObject中的元素。我需要訪問'applicationID',但遇到麻煩很麻煩。我已經成功地從下面的代碼創建的SimpleXmlObject:(我的10響應文檔的截短9)包含responseHeader的PHP SimpleXML

<response> 
    <lst name='responseHeader'> 
     <int name='status'>0</int> 
     <lst name='params'> 
     <str name='q'>applicationDateAdded:NOW()-1</str> 
     <str name='wt'>xml</str> 
     </lst> 
    </lst> 
    <result name='response' numFound='10' start='0'> 
     <doc> 
     <date name='applicationDateAdd'>2012-02-28T16:00:00Z</date> 
     <arr name='applicationDescript'> 
      <str>description</str> 
      <str>desc</str> 
     </arr> 
     <bool name='applicationFeatured'>false</bool> 
     <str name='applicationId'>APPID-00000000017</str> 
     <str name='id'>APPID-00000000017</str> 
     <str name='type'>APPLICATION</str> 
     </doc> 
     <doc>...</doc> 
     <doc>...</doc> 
     <doc>...</doc> 
     <doc>...</doc> 
     <doc>...</doc> 
     <doc>...</doc> 
     <doc>...</doc> 
     <doc>...</doc> 
     <doc>...</doc> 
    </result> 
</response> 

回答

0

這將回聲出每個的applicationID的值(假設XML字符串是在$xml):

$xmlObj = simplexml_load_string($xml); 

foreach($xmlObj->result->doc as $doc) 
{ 
    foreach($doc->str as $str) 
    { 
     if($str->attributes()->name == 'applicationId') 
     { 
      echo 'applicationId: ' . (string)$str . '<br />'; 
      break 1; 
     } 
    } 
} 
1

謝謝你的幫忙!我在一個月前解決了這個問題(並且忘記了我已經在這裏發佈到現在)。雖然我的解決方案有點少年並且可以根據我的需求進行定製,但我很樂意幫助有類似問題的任何人。以下循環並給出每個屬性的值:

// $results is the SimpleXmlElement object at the beginning 
$numFound = $results -> attributes() -> numFound; 
    echo "Number of Results found: "; 
    echo $numFound; 
    echo '<br><br>'; 

    if ($numFound > 0) { 
    foreach($results -> children() as $content) { 
     echo '<br>------------------------<br>'; 
     foreach ($content -> children() as $sub) { 
     $attName = $sub -> attributes(); 
     echo $attName[0]." = "; 
     $count = 0; 
     foreach($sub -> children() as $val) { 
     $val = $sub -> str[$count++]; 
     echo $val; 
      echo '<br>'; 
     } 
     echo '<br>'; 
     } 
    } 
    }