这段代码使用 curl 和 json 有什么问题?

我有这段代码,我想在 curl 响应中获取“项目”的所有数据,当我使用浏览器访问 URL 时,它会显示所有“项目”,但是使用这段代码,curl 响应正在工作,但是“items”为空,代码如下:


$eop = 0;

$newest = 0;


while($eop == 0) {


    $url='https://shopee.ph/api/v2/search_items/?by=ctime&limit=30&match_id=49133756&newest=0&order=desc&page_type=shop&version=2';     


    $ch = curl_init($url);      

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     

    $response = curl_exec($ch);     

    $http = curl_getinfo($ch, CURLINFO_HTTP_CODE);  


    print_r($response);


    curl_close($ch);


    if ($http == 200) { 


    $products = @json_decode($response, TRUE);          


        $items = $products['items'];


        if (count($items) > 1 ) {


           foreach ($items as $item) { 


            $id = $item['itemid'];          

            echo $id . '<br>';


        }


        } else {

            $eop=1;

        }



    }


    $newest = $newest + 30;

}

这是回应:


{"show_disclaimer":null,"query_rewrite":null,"adjust":null,"version":"b1c94828d525e526ff969f451cc3ac33","algorithm":null,"total_count":null,"error":null,"total_ads_count":null,"nomore":null,"price_adjust":null,"json_data":null,"suggestion_algorithm":null,"items":null,"reserved_keyword":null,"hint_keywords":null}


白板的微信
浏览 76回答 1
1回答

慕田峪7331174

随机猜测后,我发现如果您不提供 User-Agent 标头,指定的 API 将不会返回任何项目。这是我的版本:<?php$eop = 0;$newest = 0;while($eop == 0) {&nbsp; &nbsp; $url='https://shopee.ph/api/v2/search_items/?by=ctime&limit=30&match_id=49133756&newest=0&order=desc&page_type=shop&version=2';&nbsp; &nbsp; $ch = curl_init($url);&nbsp; &nbsp; curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);&nbsp; &nbsp; curl_setopt($ch, CURLOPT_HTTPHEADER, array("user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36"));&nbsp; &nbsp; $response = curl_exec($ch);&nbsp; &nbsp; $http = curl_getinfo($ch, CURLINFO_HTTP_CODE);&nbsp; &nbsp; print_r($response);&nbsp; &nbsp; curl_close($ch);&nbsp; &nbsp; if ($http == 200) {&nbsp; &nbsp; $products = json_decode($response, TRUE);&nbsp; &nbsp; &nbsp; &nbsp; $items = $products['items'];&nbsp; &nbsp; &nbsp; &nbsp; if (count($items) > 1 ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;foreach ($items as $item) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $id = $item['itemid'];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo $id . '<br>';&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $eop=1;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; $newest = $newest + 30;}
打开App,查看更多内容
随时随地看视频慕课网APP