Check current stream time with PHP and record time to CSV

Hello!
I have a rather simple task - to check time in
https://api.twitch.tv/kraken/channels/johnnyinthedark/videos?client_id=XXXX&broadcast_type=archive&limit=1
and save some fields to csv.

Unfortunately I don’t have enough expertise in PHP to make it work myself. I have tried 10 different scripts but none of them worked so far. Can someone help me with a simple script that saves json data from that url to CSV?

<?php
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_HTTPHEADER, array(
		'Accept: application/vnd.twitchtv.v5+json',
        'Client-ID: client_id_here'
	));

	curl_setopt($curl, CURLOPT_URL, 'https://api.twitch.tv/kraken/channels/115084217/videos?broadcast_type=archive&limit=1');
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	$results = json_decode(curl_exec($curl));
    $output_file = fopen('output.csv', 'a');  // Append data with 'a' while 'w' overwrites the file
    
    // Uncomment the following if you want to print to stdout the data in a readable format.
    // print_r($results);

    foreach($results->videos as $video) {
        print_r($video->created_at);
        fputs($output_file, 'created_at,'.$video->created_at.PHP_EOL);   // PHP_EOL writes a new line
    }
    fclose($output_file);
?>
[morpheus] /opt/iobot2
illusion% !php
php ./getData.php 
2017-08-20T11:59:48Z

Note that since the API v3 is going away, I am calling v5.

2 Likes

Wow, it works right out of the box! I just have 1 problem, it replaces csv completely with new data instead of adding a new line and keeping old records. Can this be changed?

Btw still using Phantombot, it’s getting better and better ) Moved it to dedicated server, got front-end to check points. My viewers are loving it.

1 Like

Sorry, yes! See my changes above with notes.

1 Like

Perfect script. Owe you big time. Thanks a lot!

1 Like

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