Getting viewer count with php and curl

At the moment I’m busy with finding a solution to make the following script work:

<?php
function file_get_contents_curl($url) {
$ch = curl_init();

curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);       
curl_setopt($ch, CURLOPT_HTTPHEADER, 'Client-ID: CLIENT-ID');

$data = curl_exec($ch);
curl_close($ch);

return $data;
}

$url = 'https://api.twitch.tv/helix/streams?user_login='.$_GET['name'];
$json_array = json_decode(file_get_contents_curl($url), true);

echo $json_array['data']['viewer_count'];
?>

I thought with this specific code, I could retrieve a viewer_count. Whats isn’t happening. What do I do wrong?

Try:


function file_get_contents_curl($url) {
	$ch = curl_init();

	curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);     
	curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		'Client-ID: CLIENT-ID'
	));

	$data = curl_exec($ch);
	curl_close($ch);
	return $data;
}

$url = 'https://api.twitch.tv/helix/streams?user_login='.$_GET['name'];
$json_array = json_decode(file_get_contents_curl($url), true);

echo $json_array['data'][0]['viewer_count'];

shove a print_r($json_array); after this and you can debug you own script.

or just use the solution provided.

Helix api returns a JSON object with a key of data. and data is always an array, so you need to refer to the first entry in said array

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