How can I convert my API code from JSON to cURL


#1

Hi guys,

I’m recently upgraded my server’s PHP version which has caused an error with my JSON code:

$channelName = PixelGumTV
$clientId = 'xxxxxxxxxxxxxxxxxxxxxxxxxx';
$json_array = json_decode(file_get_contents('https://api.twitch.tv/kraken/streams/'.strtolower($channelName).'?client_id='.$clientId), true);
 
if ($json_array['stream'] != NULL) {
    $channelTitle = $json_array['stream']['channel']['display_name'];
    $streamTitle = $json_array['stream']['channel']['status'];
    $currentGame = $json_array['stream']['channel']['game'];
}

Can anyone tell me how I can convert this code so I can obtain exactly the same information? ($channelTitle, $streamTitle, & $currentGame).

Many thanks!


#2

I don’t do a lot in PHP but always preferred GuzzleHttp. The channel ID below belongs to PixelGumTV as I am using v5, I think you are defaulting to v3 based on the code up there and that is about to be made the non-default and third-party support removed early this year.

$client = new GuzzleHttp\Client();

try
{
    $response = $client->request('GET',
                                'https://api.twitch.tv/kraken/streams/115850044',
                                [ 'headers' => [
                                    'Client-ID' => 'myclientID',
                                    'Accept' => 'application/vnd.twitchtv.v5+json' ]
                                ]);

    $result = $response->getBody();
    $object = json_decode($result);
    var_dump($object);
}
catch (Exception $e)
{
    $result = $e->getResponse();
    var_dump($result);
}   

Right now, offline so just returns NULL:

illusion% php ./test_twitch.php 
object(stdClass)#31 (1) {
  ["stream"]=>
  NULL
}

So, swapped to the channels endpoint:

illusion% php ./test_twitch.php 
object(stdClass)#31 (23) {
  ["mature"]=>
  bool(false)
  ["status"]=>
  string(82) "S2 Ep.174: Multiplayer Madness! | DAILY STREAM | !schedule !grab !pixelpot !coffee"
  ["broadcaster_language"]=>
  string(2) "en"
  ["broadcaster_software"]=>
  string(12) "unknown_rtmp"
  ["display_name"]=>
  string(10) "PixelGumTV"
  ["game"]=>
  string(24) "The Jackbox Party Pack 4"
.......

#3

Additional notes here on your duplicate post


#4

To one of Barry’s points, from hitting Google, file_get_contents() is known to have hiccups. Perhaps you could try the refactor as I indicate above and see what happens. If that fails then I think Barry has outlined any other possible issues as they relate to certificates.