【问题标题】:PHP cURL requests being slowPHP cURL 请求很慢
【发布时间】:2021-01-25 15:12:01
【问题描述】:

我试图从我的循环的每次迭代中更改的 URL(它是一个 json)中获取内容。我做事的方法的问题是它非常慢,如果我进行大约 120 次迭代,则需要 40 多秒。

这是我的代码:

$GetFriendListUrl = "http://api.steampowered.com/ISteamUser/GetFriendList/v0001/?key=mykey&steamid=".$other_steamid."&relationship=friend";
$GET_GetFriendListUrl= file_get_contents($GetFriendListUrl);

$raw_ids = json_decode($GET_GetFriendListUrl , TRUE);
$count = count($raw_ids['friendslist']['friends']);

$ci = curl_init();
curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);

for ($x = 0; $x <= $count; $x++) {
    $friendslist = $raw_ids['friendslist']['friends'][$x]['steamid'];

    curl_setopt($ci, CURLOPT_URL, "https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=mykey&steamids=".$friendslist);
    $cont = curl_exec($ci);
    $contFull = json_decode($cont, true);

    $steamname = $contFull['response']['players'][0]['personaname'];
    $steamprofileurl = $contFull['response']['players'][0]['profileurl'];
    $friendimage = $contFull['response']['players'][0]['avatar'];
 
    $friendimageData = base64_encode(file_get_contents($friendimage));

    echo '<img class="other_friendsteamimage" src="data:image/jpeg;base64,'.$friendimageData.'">';
    echo "<a class='other_friendlabel' href='$steamprofileurl'>$steamname</a>";
    echo "<br>";
}
curl_close($ci);

【问题讨论】:

  • 文档建议您可以提供"Comma-delimited list of 64 bit Steam IDs to return profile information for. Up to 100 Steam IDs can be requested." - 这样做可以节省大量时间

标签: php css api curl steam


【解决方案1】:

我无法确定 api 返回的数据的格式,我无法测试以下内容,但根据我所做的评论,并且根据文档,似乎发送的请求很少,但每个请求处理 100 个 steamID 应该可以节省大量时间。

/* get the intial data */
$url = "http://api.steampowered.com/ISteamUser/GetFriendList/v0001/?key=mykey&steamid=".$other_steamid."&relationship=friend";
$data= file_get_contents( $url );


$json = json_decode( $data );
$ids=array();

/* just grab the IDs and add to array - correct format to access records??? */
foreach( $json->friendslist->friends as $obj ){
    $ids[]=$obj->steamid;
}

/* split the IDs into chunks of 100 */
$chunks=array_chunk( $ids, 100 );


/* send a request per chunk of 100 */
foreach( $chunks as $chunk ){

    $url=sprintf('https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=mykey&steamids=%s',implode(',',$chunk));
    $curl = curl_init( $url );
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $res=curl_exec( $curl );
    if( $res ){
        $data=json_decode($res,true);
        /* do stuff .... */
    }
    curl_close($curl);
}

echo 'Finito';

【讨论】:

    猜你喜欢
    • 2017-01-29
    • 1970-01-01
    • 1970-01-01
    • 2013-03-24
    • 1970-01-01
    • 2018-06-28
    • 2019-09-03
    • 2016-04-15
    • 2012-11-05
    相关资源
    最近更新 更多