Search code examples
phparraysamazon-product-advertising-api

PHP result produces an Array sometimes not and I'm getting this error "Cannot use string offset"


I am getting an inconsistent result, sometimes I am getting an array and sometimes I think I am not getting an array because it triggers this kind of error:

Fatal error: Cannot use string offset as an array in /home/loc/public_html/mysite.com/directory/home/test.php on line 25

This is my code:

$result = $response['Items']['Item'];
    $html = "";
    foreach( $result as $k => $v ){
        if(isset($v['MediumImage'])) {
            $image = "<img src='".$v['MediumImage']['URL']."' />";
        }else if(isset($v['LargeImage'])) {
            $image = "<img width='150px' height='150px' src='".$v['LargeImage']['URL']."' />";
        }else {
            $image = "<img src='css/no-image.jpg' />";
        }
        $html .= "<div class='container'>";
        $html .= "<div class='imgContainer'><a href='".$v['DetailPageURL']."'>".$image."</a></div>";
        $html .= "<h3 class='newaps'><a href='".$v['DetailPageURL']."'><span class='lrg bold'>".$v['ItemAttributes']['Title']."</span></a></h3>";
        if(isset($v['ItemAttributes']['Feature'])){
            $html .= "<div class='item-features'>";
            $html .= "<ul>";
            foreach( $v['ItemAttributes']['Feature'] as $feature ) {
                $html .= "<li>".$feature."</li>";
            }
            $html .= "</ul>";
            $html .= "</div>";
        } else {
            $html .= "<div class='item-features'>";
            $html .= "<span class='no-data'><a href='".$v['DetailPageURL']."'>More info on this item...</a></span>";
            $html .= "</div>";
        }
        $html .= "<div class='clear'></div>";
        if(isset($v['ItemAttributes']['ListPrice'])){
            $html .= "<div class='item-price'>Price: ".$v['ItemAttributes']['ListPrice']['FormattedPrice']." ".$v['ItemAttributes']['ListPrice']['CurrencyCode']."</div>";
        }
        $html .= "<div class='trackSalesRank' id='".$v['ASIN']."'>Track Sales Rank</div>";
        $html .= "</div>";

Line 25 is $image = "<img src='".$v['MediumImage']['URL']."' />";

This is the array value of $response:

Array
(
    [OperationRequest] => Array
        (
            [HTTPHeaders] => Array
                (
                    [Header] => Array
                        (
                            [Name] => UserAgent
                            [Value] => PHP-SOAP/5.3.19
                        )

                )

            [RequestId] => 74dd6e53-5455-4852-8b19-72580b3f244d
            [Arguments] => Array
                (
                    [Argument] => Array
                        (
                            [Name] => Service
                            [Value] => AWSECommerceService
                        )

                )

            [RequestProcessingTime] => 0.319231
        )

    [Items] => Array
        (
            [Request] => Array
                (
                    [IsValid] => True
                    [ItemSearchRequest] => Array
                        (
                            [ItemPage] => 1
                            [Keywords] => B0083PWAPW
                            [ResponseGroup] => Array
                                (
                                    [0] => Images
                                    [1] => ItemAttributes
                                )

                            [SearchIndex] => All
                        )

                )

            [TotalResults] => 1
            [TotalPages] => 1
            [MoreSearchResultsUrl] => http://www.amazon.com/gp/redirect.html?camp=2025&creative=386001&location=http%3A%2F%2Fwww.amazon.com%2Fgp%2Fsearch%3Fkeywords%3DB0083PWAPW%26url%3Dsearch-alias%253Daws-amazon-aps&linkCode=sp1&tag=elson06-20&SubscriptionId=AKIAJJPPYQPVMQLOYLKQ
            [Item] => Array
                (
                    [ASIN] => B0083PWAPW
                    [ParentASIN] => B008GGCAVM
                    [DetailPageURL] => http://www.amazon.com/Kindle-Fire-HD/dp/B0083PWAPW%3FSubscriptionId%3DAKIAJJPPYQPVMQLOYLKQ%26tag%3Delson06-20%26linkCode%3Dsp1%26camp%3D2025%26creative%3D165953%26creativeASIN%3DB0083PWAPW
                    [ItemLinks] => Array
                        (
                            [ItemLink] => Array
                                (
                                    [0] => Array
                                        (
                                            [Description] => Technical Details
                                            [URL] => http://www.amazon.com/Kindle-Fire-HD/dp/tech-data/B0083PWAPW%3FSubscriptionId%3DAKIAJJPPYQPVMQLOYLKQ%26tag%3Delson06-20%26linkCode%3Dsp1%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB0083PWAPW
                                        )

                                    [1] => Array
                                        (
                                            [Description] => Add To Baby Registry
                                            [URL] => http://www.amazon.com/gp/registry/baby/add-item.html%3Fasin.0%3DB0083PWAPW%26SubscriptionId%3DAKIAJJPPYQPVMQLOYLKQ%26tag%3Delson06-20%26linkCode%3Dsp1%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB0083PWAPW
                                        )

                                    [2] => Array
                                        (
                                            [Description] => Add To Wedding Registry
                                            [URL] => http://www.amazon.com/gp/registry/wedding/add-item.html%3Fasin.0%3DB0083PWAPW%26SubscriptionId%3DAKIAJJPPYQPVMQLOYLKQ%26tag%3Delson06-20%26linkCode%3Dsp1%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB0083PWAPW
                                        )

                                    [3] => Array
                                        (
                                            [Description] => Add To Wishlist
                                            [URL] => http://www.amazon.com/gp/registry/wishlist/add-item.html%3Fasin.0%3DB0083PWAPW%26SubscriptionId%3DAKIAJJPPYQPVMQLOYLKQ%26tag%3Delson06-20%26linkCode%3Dsp1%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB0083PWAPW
                                        )

                                    [4] => Array
                                        (
                                            [Description] => Tell A Friend
                                            [URL] => http://www.amazon.com/gp/pdp/taf/B0083PWAPW%3FSubscriptionId%3DAKIAJJPPYQPVMQLOYLKQ%26tag%3Delson06-20%26linkCode%3Dsp1%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB0083PWAPW
                                        )

                                    [5] => Array
                                        (
                                            [Description] => All Customer Reviews
                                            [URL] => http://www.amazon.com/review/product/B0083PWAPW%3FSubscriptionId%3DAKIAJJPPYQPVMQLOYLKQ%26tag%3Delson06-20%26linkCode%3Dsp1%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB0083PWAPW
                                        )

                                    [6] => Array
                                        (
                                            [Description] => All Offers
                                            [URL] => http://www.amazon.com/gp/offer-listing/B0083PWAPW%3FSubscriptionId%3DAKIAJJPPYQPVMQLOYLKQ%26tag%3Delson06-20%26linkCode%3Dsp1%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB0083PWAPW
                                        )

                                )

                        )

                    [SmallImage] => Array
                        (
                            [URL] => http://ecx.images-amazon.com/images/I/51EN7cswSYL._SL75_.jpg
                            [Height] => Array
                                (
                                    [_] => 75
                                    [Units] => pixels
                                )

                            [Width] => Array
                                (
                                    [_] => 75
                                    [Units] => pixels
                                )

                        )

                    [MediumImage] => Array
                        (
                            [URL] => http://ecx.images-amazon.com/images/I/51EN7cswSYL._SL160_.jpg
                            [Height] => Array
                                (
                                    [_] => 160
                                    [Units] => pixels
                                )

                            [Width] => Array
                                (
                                    [_] => 160
                                    [Units] => pixels
                                )

                        )

                    [LargeImage] => Array
                        (
                            [URL] => http://ecx.images-amazon.com/images/I/51EN7cswSYL.jpg
                            [Height] => Array
                                (
                                    [_] => 500
                                    [Units] => pixels
                                )

                            [Width] => Array
                                (
                                    [_] => 500
                                    [Units] => pixels
                                )

                        )

                    [ImageSets] => Array
                        (
                            [ImageSet] => Array
                                (
                                    [SwatchImage] => Array
                                        (
                                            [URL] => http://ecx.images-amazon.com/images/I/51EN7cswSYL._SL30_.jpg
                                            [Height] => Array
                                                (
                                                    [_] => 30
                                                    [Units] => pixels
                                                )

                                            [Width] => Array
                                                (
                                                    [_] => 30
                                                    [Units] => pixels
                                                )

                                        )

                                    [SmallImage] => Array
                                        (
                                            [URL] => http://ecx.images-amazon.com/images/I/51EN7cswSYL._SL75_.jpg
                                            [Height] => Array
                                                (
                                                    [_] => 75
                                                    [Units] => pixels
                                                )

                                            [Width] => Array
                                                (
                                                    [_] => 75
                                                    [Units] => pixels
                                                )

                                        )

                                    [ThumbnailImage] => Array
                                        (
                                            [URL] => http://ecx.images-amazon.com/images/I/51EN7cswSYL._SL75_.jpg
                                            [Height] => Array
                                                (
                                                    [_] => 75
                                                    [Units] => pixels
                                                )

                                            [Width] => Array
                                                (
                                                    [_] => 75
                                                    [Units] => pixels
                                                )

                                        )

                                    [TinyImage] => Array
                                        (
                                            [URL] => http://ecx.images-amazon.com/images/I/51EN7cswSYL._SL110_.jpg
                                            [Height] => Array
                                                (
                                                    [_] => 110
                                                    [Units] => pixels
                                                )

                                            [Width] => Array
                                                (
                                                    [_] => 110
                                                    [Units] => pixels
                                                )

                                        )

                                    [MediumImage] => Array
                                        (
                                            [URL] => http://ecx.images-amazon.com/images/I/51EN7cswSYL._SL160_.jpg
                                            [Height] => Array
                                                (
                                                    [_] => 160
                                                    [Units] => pixels
                                                )

                                            [Width] => Array
                                                (
                                                    [_] => 160
                                                    [Units] => pixels
                                                )

                                        )

                                    [LargeImage] => Array
                                        (
                                            [URL] => http://ecx.images-amazon.com/images/I/51EN7cswSYL.jpg
                                            [Height] => Array
                                                (
                                                    [_] => 500
                                                    [Units] => pixels
                                                )

                                            [Width] => Array
                                                (
                                                    [_] => 500
                                                    [Units] => pixels
                                                )

                                        )

                                    [Category] => primary
                                )

                        )

                    [ItemAttributes] => Array
                        (
                            [Binding] => Electronics
                            [Brand] => Kindle
                            [CatalogNumberList] => Array
                                (
                                    [CatalogNumberListElement] => 53-000406
                                )

                            [EAN] => 2609000005244
                            [EANList] => Array
                                (
                                    [EANListElement] => Array
                                        (
                                            [0] => 2609000005244
                                            [1] => 2609000006326
                                            [2] => 2609000009471
                                            [3] => 0848719003796
                                            [4] => 2609000009136
                                            [5] => 2609000005497
                                            [6] => 2609000006364
                                            [7] => 2720320491521
                                            [8] => 2609000006388
                                            [9] => 2609000009327
                                        )

                                )

                            [Feature] => Array
                                (
                                    [0] => Stunning 1280x800 HD display with rich color and deep contrast from any viewing angle
                                    [1] => Exclusive Dolby audio and dual driver stereo speakers for crisp, booming sound without distortion
                                    [2] => Ultra-fast Wi-Fi- dual-antenna, dual-band Wi-Fi for 35% faster downloads and streaming
                                    [3] => Over 22 million movies, TV shows, songs, magazines, books, audiobooks, and popular apps and games
                                )

                            [ItemDimensions] => Array
                                (
                                    [Height] => Array
                                        (
                                            [_] => 40
                                            [Units] => hundredths-inches
                                        )

                                    [Length] => Array
                                        (
                                            [_] => 760
                                            [Units] => hundredths-inches
                                        )

                                    [Weight] => Array
                                        (
                                            [_] => 87
                                            [Units] => hundredths-pounds
                                        )

                                    [Width] => Array
                                        (
                                            [_] => 540
                                            [Units] => hundredths-inches
                                        )

                                )

                            [Label] => Amazon Digital Services, Inc
                            [ListPrice] => Array
                                (
                                    [Amount] => 19900
                                    [CurrencyCode] => USD
                                    [FormattedPrice] => $199.00
                                )

                            [Manufacturer] => Amazon Digital Services, Inc
                            [Model] => 53-000406
                            [MPN] => 0379
                            [PackageDimensions] => Array
                                (
                                    [Height] => Array
                                        (
                                            [_] => 140
                                            [Units] => hundredths-inches
                                        )

                                    [Length] => Array
                                        (
                                            [_] => 1010
                                            [Units] => hundredths-inches
                                        )

                                    [Weight] => Array
                                        (
                                            [_] => 115
                                            [Units] => hundredths-pounds
                                        )

                                    [Width] => Array
                                        (
                                            [_] => 740
                                            [Units] => hundredths-inches
                                        )

                                )

                            [PackageQuantity] => 1
                            [PartNumber] => 0379
                            [ProductGroup] => Amazon Devices
                            [ProductTypeName] => ABIS_ELECTRONICS
                            [Publisher] => Amazon Digital Services, Inc
                            [ReleaseDate] => 2012-09-14
                            [Studio] => Amazon Digital Services, Inc
                            [Title] => Kindle Fire HD 7", Dolby Audio, Dual-Band Wi-Fi, 16 GB - Includes Special Offers
                            [UPC] => 848719003796
                            [UPCList] => Array
                                (
                                    [UPCListElement] => 848719003796
                                )

                        )

                )

        )

)

I know it's kinda long. but I am getting inconsistent results, sometimes processing the code works perfectly, but sometimes it triggers an error "Cannot use string offset". Why is this happening?

PS: The array response came from Amazon Product Advertising API, I know this is not an important detail, incase you are wondering :)


Solution

  • The response that you are getting from amazon is not same for all the products. Some products have some extra data and some dont have those

    Eg: product attributes will vary for different products (t-shirt, mobile phone)

    some products may have offer price

    (If offer price is there for a product it will be a in 'offer' ['item']['offer'], So first you check for this offset if it is not there take the price from attributes tage(price will be shown there in amazon response))

    So before you print or process the data, Check for the key in array get the value only in key exists.

    In your case :

    $result = $response['Items']['Item'];
    $html = "";
    foreach( $result as $k => $v ){
      if($k == "MediumImage"){
          echo $v['URL'];
      }
    }
    

    What you have done is wrong you will not get $v["MediumImage"] here.