2010-02-25 48 views
1

我使用CloudFusion類來獲得Amazon.com的數據和我的代碼很簡單:如何正確解析PHP中的SimpleXML對象?

$items = $pas->item_search("shoes", array( 
    "ResponseGroup" => "Small", 
    "SearchIndex" => "Blended")); 
$items = $items->body->Items; 
echo "<pre>"; 
print_r($items); 
echo "</pre>"; 

這將返回以下:

SimpleXMLElement Object (
    [Request] => SimpleXMLElement Object 
     (
      [IsValid] => True 
      [ItemSearchRequest] => SimpleXMLElement Object 
       (
        [Keywords] => shoes 
        [ResponseGroup] => Small 
        [SearchIndex] => Blended 
       ) 

     ) 

    [TotalResults] => 737435 
    [TotalPages] => 245816 
    [SearchResultsMap] => SimpleXMLElement Object 
     (
      [SearchIndex] => Array 
       (
        [0] => SimpleXMLElement Object 
         (
          [IndexName] => Kitchen 
        .... 
     ) 

    [Item] => Array 
     (
      [0] => SimpleXMLElement Object 
       (
        [ASIN] => B0001Z95QY 
        [DetailPageURL] => http://www.amazon.com/Household-Essentials-MS6030-Seasonal-Storage/dp/B0001Z95QY%3FSubscriptionId%3D0WASFFPR5B82TH4ZQB82%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3DB0001Z95QY 
        [ItemLinks] => SimpleXMLElement Object 
         (
          [ItemLink] => Array 
           (
            [0] => SimpleXMLElement Object 
             (
              [Description] => Technical Details 
              [URL] => http://www.amazon.com/Household-Essentials-MS6030-Seasonal-Storage/dp/tech-data/B0001Z95QY%3FSubscriptionId%3D0WASFFPR5B82TH4ZQB82%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB0001Z95QY 
             ) .................... 
       ) 

      [1] => SimpleXMLElement Object 
       (
        [ASIN] => B001ACNBZ8 
        [DetailPageURL] => http://www.amazon.com/Peet-Shoe-Dryer-Boot-Original/dp/B001ACNBZ8%3FSubscriptionId%3D0WASFFPR5B82TH4ZQB82%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3DB001ACNBZ8 
        [ItemLinks] => SimpleXMLElement Object 
         (................... 
     ) 

) 

我希望做的是踏踏實實到「Item」級別,然後運行foreach以獲取每個單獨的條目。我試過$items = $items->Item,但是這隻返回第一個條目。

任何想法?

回答

0

首先,您應該避免在SimpleXMLElement上使用print_r(),而應該使用asXML()來查看XML。這也是你應該在這裏發佈,而不是print_r()的輸出。

我認不出你已經發布的代碼,所以我就來猜猜,建議大家嘗試類似:

foreach ($items->body->Items->Item as $Item) 
{ 
} 

無論如何,如果你想遍歷的東西,的foreach是答案。