I am trying to cache the entirety of streams from Twitch.TV public API with the following code. It is successful but takes almost a full minute to execute so I am wondering if it's my code or just the speed of the API delivery. In any case, because it is my first PHP script (and really, I'm new in general), I am certain there are logical missteps and performance crushing flows and I would appreciate some review!
The function buildPages()
is mainly what is in question for this post.
The data is always returned as json and I dump it all to disk for local testing. Suggestions on how to implement an accelerator for this collection are welcomed since I've never played with one before. APC or Memcache(d)? I have a lot of reading to do..
Also, I am not certain why the lines
$length = count($page->streams);
$length = count($page['streams']);
had to be written as such. stdClass
Object versus ArrayAccess
? I don't really understand why I would get errors when trying to use the same accessor in the case of my code. Is $page
not always an associative array created from the JSON data?
<?php
$base = 'https://api.twitch.tv/kraken/';
$thatlist = array(
'games'=> array(
'url'=>'games/top',
'params'=> array(
'limit'=>100,
'offset'=>0
)
),
'featured'=>array(
'url'=>'streams/featured',
'params'=>array(
'limit'=>100,
'offset'=>0
)
),
'summary'=>array(
'url'=>'streams/summary',
'params'=>array(
'limit'=>100,
'offset'=>0
)
),
'teams'=>array(
'url'=>'teams',
'params'=>array(
'limit'=>100,
'offset'=>0
)
)
);
foreach($thatlist as $key => $val) {
$fullurl = $base . $val['url'];
foreach($val['params'] as $foo => $bar){
$fullurl .= '?' . $foo . '=' . $bar;
}
$quicklist[$key] = json_decode(file_get_contents($fullurl), true);
}
function buildPages() {
$streams = array();
$offset = 0;
$page = json_decode(file_get_contents("https://api.twitch.tv/kraken/streams?offset=".$offset."&limit=100", true));
$length = count($page->streams);
array_push($streams, $page);
// request always returns 100 items unless at the end of live data
while($length = 100) {
$index = count($streams);
$offset = $index * 100;
$page = json_decode(file_get_contents("https://api.twitch.tv/kraken/streams?offset=".$offset.'&limit=100'), true);
$length = count($page['streams']);
echo "Index: ".$index."<br/>";
echo "Length: ".$length."<br/>";
array_push($streams, $page);
}
var_dump($streams);
$sd = fopen('streams-dump.json', 'w');
fwrite($sd, json_encode($streams));
fclose($sd);
}
$qld= fopen('quicklist-dump.json', 'w');
fwrite($qld, json_encode($quicklist));
fclose($qld);
buildPages();
?>
$offset = 2500
and a few streams back from$offset = 300
drop, won't it screw up everything? \$\endgroup\$