JSON / cURL - 尝试解码GET请求的结果

时间:2016-06-27 16:18:23

标签: php json curl

这是我的代码(CURL)

<?php
$url = "http://www.sportsdirect.com/DesktopModules/ProductDetail/API/ItemSuggestions/GetProductSuggestions?productId=433006&numPlacements=1&ItemType=product";
//  Initiate curl
$ch = curl_init();
        curl_setopt($ch, CURLOPT_COOKIE, "ChosenSite=www; SportsDirect_AnonymousUserCurrency=GBP; language=en-GB");
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSLVERSION, 3);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
        curl_setopt($ch, CURLOPT_VERBOSE, true);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);

// Will dump a beauty json :3
$collections = json_decode($result);

    foreach ($collections as $item) {
        $Title = $item->Products->Title;            

        echo $Title;
    }

使用此代码我收到空白屏幕,不会打印任何结果。 我想要的只是echo所有产品的所有Title名称。

我的错误在哪里,我怎样才能实现我的目标?

2 个答案:

答案 0 :(得分:1)

使用以下代码。它会对你有所帮助。

foreach ($collections as $row){
foreach ($row->Products as $item) {
    $Title = $item->Title;            

    echo $Title;
}

}

答案 1 :(得分:0)

这是因为$ item-&gt; Products是一个数组。你想做这样的事情:

foreach ($collections as $item) {
    foreach($item->Products AS $product){
        $Title = $product->Title;            
        echo $Title;
    }
}