New Twitch API code

Hello!
Help configure the script.
Gives an error message.

   Warning: file_get_contents(http://api.twitch.tv/kraken/streams?limit=100&offset=0) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in Z:\home\localhost\www\twitch\tw_get_channels.php on line 22

Warning: Invalid argument supplied for foreach() in Z:\home\localhost\www\twitch\tw_get_channels.php on line 23

Here is the code.

<?php

header( 'Content-type: text/html; charset=utf-8' );
set_time_limit(-1);

$minViewers = 50;
$maxScan = 500;

$filenameRu = 'rusteams.txt';
$filenameAll = 'steams.txt';


// ---------------------------------------------

file_put_contents($filenameRu, '');
file_put_contents($filenameAll, '');

for ($offset = 0; $offset <= $maxScan; $offset += 100){
	echo "$offset/$maxScan <br>", PHP_EOL;
	flush();
    ob_flush();
	$json = json_decode(file_get_contents("http://api.twitch.tv/kraken/streams?limit=100&offset=$offset"));
	foreach ($json->streams as $st){
		if ($st->channel->language=='ru' && $st->viewers > $minViewers) file_put_contents($filenameRu, $st->channel->name.PHP_EOL, FILE_APPEND);
		file_put_contents($filenameAll, $st->channel->name.PHP_EOL, FILE_APPEND);
	}

}

// удаляем дубли и сортируем полученные файлы стримов
clearAndSort($filenameAll);
clearAndSort($filenameRu);

echo "[Finished]";

function clearAndSort ($filename){
	$steams = file($filename);
	$steams = array_unique($steams);
	sort($steams);
	array_shift($steams);
	file_put_contents($filename, implode($steams, ''));
}
  1. The request should be https, not http
  2. You aren’t passing your client ID
1 Like
  1. you can’t handle errors with file_get_contents, should use the curl library
1 Like
  1. Don’t use file_get_contents it doesn’t work on a lot of web hosts and you just shouldn’t use it for http calls like ever
1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.