John Hayes John Hayes - 7 months ago 18
PHP Question

Invalid argument supplied for foreach() When spaces are present

I am making a website that uses the twitch api that searches through the games and lists the streams that are playing said game. Everything works great, except for when I get an error when searching for games that have a space in them. For example, it will list the minecraft streams, but gets an error when trying to do League of Legends.

<?php
$game = $_GET['game'];
$json_file = @file_get_contents("https://api.twitch.tv/kraken/streams?game{$game}", 0, null, null);
$json = json_decode($json_file);
foreach ($json->streams as $stream) {
echo($stream->channel->name);
echo "<br>";
}
?>

Answer

Use urlencode to prepare the string to be used in an url:

$game = $_GET['game']
$game = urlencode($game);
$json_file = @file_get_contents("https://api.twitch.tv/kraken/streams?game{$game}", 0, null, null); 
Comments