Skip to content

Instantly share code, notes, and snippets.

@Xhynk
Created August 21, 2020 21:44
Show Gist options
  • Save Xhynk/59d9aab86a70195ea744dfcf777dabec to your computer and use it in GitHub Desktop.
Save Xhynk/59d9aab86a70195ea744dfcf777dabec to your computer and use it in GitHub Desktop.
A simple PHP function to help grab your most recent Stack Exchange values for use in your website.
<?php
function get_stack_exchange_data( int $stack_exchange_id, bool $force_refresh = false, string $cache_dir = __DIR__ . '/stack-exchange' ){
$max_age = 1800;
$api_url = sprintf( 'https://api.stackexchange.com/2.2/users/%d/associated', $stack_exchange_id );
$cache_name = sprintf( '%s/%d.txt', $cache_dir, $stack_exchange_id );
if( !is_dir($cache_dir) )
mkdir( $cache_dir );
if( !file_exists($cache_name) || (file_exists($cache_name) && filemtime($cache_name) < ( time() - $max_age )) ){
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $api_url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_ENCODING , 'gzip' );
$data = curl_exec( $ch );
try {
file_put_contents( $cache_name, $data );
} catch( Exception $e ){
trigger_error( $e->getMessage(), E_USER_WARNING );
}
} else {
$data = file_get_contents( $cache_name );
}
$data = json_decode( $data );
for( $i = 0, $n = count($data->items); $i < $n; $i++ ){
$data->items[$data->items[$i]->site_name] = $data->items[$i];
unset( $data->items[$i] );
}
return $data;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment