使用php

时间:2016-08-01 23:56:14

标签: php json

我想改进如何从API获取数据。在这种情况下,我想从Steam API中获取每个app-id,并在.txt文件中每行列出一个。我是否需要一个无限(或非常高数字)的循环(每次迭代后使用++)来获取所有人?我的意思是,从id 0开始向上计数,例如foreach - 循环?我认为它需要很长时间,听起来非常像糟糕的做法。

如何从http://api.steampowered.com/ISteamApps/GetAppList/v0001的回复中获取每个appid {"appid:" n}

<?php
    //API-URL
    $url = "http://api.steampowered.com/ISteamApps/GetAppList/v0001";
    //Fetch content and decode
    $game_json = json_decode(curl_get_contents($url), true);

    //Define file
    $file = 'steam.txt';
    //This is where I'm lost. One massive array {"app": []} with lots of {"appid": n}. 
    //I know how to get one specific targeted line, but how do I get them all?
    $line = $game_json['applist']['apps']['app']['appid'][every single line, one at a time]
    //Write to file, one id per line.
    //Like:
    //5
    //7
    //8
    //and so on
    file_put_contents($file, $line, FILE_APPEND);
?>

任何指向正确方向的人都会非常感激。谢谢!

1 个答案:

答案 0 :(得分:2)

您不必担心带有foreach循环的计数器,它们旨在通过并使用对象中的每个项目。

$file      = "steam.txt";
$game_list = "";
$url       = "http://api.steampowered.com/ISteamApps/GetAppList/v0001";
$game_json = file_get_contents($url);
$games     = json_decode($game_json);

foreach($games->applist->apps->app as $game) {
    // now $game is a single entry, e.g. {"appid":5,"name":"Dedicated server"}
    $game_list .= "$game->appid\n";
}

file_put_contents($file, $game_list);

现在你有一个包含28000个数字的文本文件。祝贺?