如何在PHP中正确解析SimpleXML对象?

时间:2010-02-25 16:05:38

标签: php simplexml

我正在使用CloudFusion类来获取Amazon.com数据,而且我的代码很简单:

$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
                        (...................
        )

)

我想做的是进入“项目”级别,然后运行foreach以获得每个单独的条目。我尝试了$items = $items->Item,但这只返回第一个条目。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

首先,您应该避免在SimpleXMLElement上使用print_r(),而只需使用asXML()查看XML。这也是你应该在这里发布的内容,而不是print_r()的输出。

我无法破译您发布的代码,因此我会猜测并建议您尝试以下内容:

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

无论如何,如果你想迭代一些东西,foreach就是答案。