So basically what I want to do is to pull in the viewer count in real time for a stream that is currently live. I have a check to see if the stream is live or not. How do you go about pinging the API constantly to get the updated value so that I can send the updated value to the document in this case it would ultimately update a the $viewers
variable that I've setup. If it makes a difference the application I'm making is using the CodeIgniter framework
. Below is the code that I currently have to make the call. Right now I have to reload the page inorder to get the actual value and it's using cURL to make the API call.
class Streaming {
var $base_url = "https://api.twitch.tv/kraken/";
var $client_id = 'client_id_here';
public function load_stream_stats($channel) {
$curl = curl_init();
curl_setopt_array($curl, array( CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $this->base_url . 'streams/'. $channel .'?client_id=' . $this->client_id
)
);
$result = curl_exec($curl);
//makes sure that the cURL was excuted if not it generates the error stating that it didn't succeed.
if(!curl_exec($curl)){
die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
} else {
//cURL Response worked
if(!empty($channel)) {
$return = json_decode($result);
if($return->stream == null) {
return;
// stream is offline no need to do anything
} else {
$stream_details = array('viewers' => $return->stream->viewers);
// $return->stream->viewers gives a number e.g. 1052
return $stream_details;
}
}
}
curl_close($curl);
}
}
The questioon in hand is how do I ping the TwitchtV API to get the updated viewer count from the REST API?