<?phpset_time_limit(300);/* $BASE is YOUR Root Endpoint ~ http://blog.hatena.ne.jp/my/config/detail*/$BASE='https://blog.hatena.ne.jp/{user}/{Hatena::Blog ID xxx.hatenablog.com}/atom/entry';/* $USER_NAME is YOUR HATENA ID*/$USER_NAME='??????';/* $PASSWORD is YOUR API key ~ http://blog.hatena.ne.jp/my/config/detail*/$PASSWORD='randomapikey00';/* OUT PUT FILE NAME (optionally file path)*/$FILENAME='/var/www/html/hatena/entrylist.json';$target=$BASE;$result=array();while(true):sleep(1);$xml_buf=get_atom_pub($target);$xml_obj=simplexml_load_string($xml_buf);$json=json_encode($xml_obj);$xml_array=json_decode($json,TRUE);foreach($xml_array['entry']as$key){if(isset($key['link'])){$result[]=array('title'=>$key['title'],'permalink'=>$key['link'][1]['@attributes']['href'],);}else{break;}}$ptn=$xml_array['link'][0]['@attributes']['href'].'?page=';$next_page_num=str_replace($ptn,'',$xml_array['link'][1]['@attributes']['href']);// echo $next_page_num . " ";if($next_page_num>0){$target=$xml_array['link'][1]['@attributes']['href'];}else{break;}endwhile;/* Write JSON File*/if(file_exists($FILENAME)&&!is_writable($FILENAME))die('Error: failed to write file');$fp=fopen($FILENAME,"w");fwrite($fp,json_encode($result));fclose($fp);echo'done';exit;functionget_atom_pub($target){global$USER_NAME,$PASSWORD;// $URL = 'https://blog.hatena.ne.jp/{user}/{Hatena::Blog ID}/atom/entry';$ch=curl_init();if(!$ch){die("Cannot initialize cURL");}curl_setopt($ch,CURLOPT_URL,$target);curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);curl_setopt($ch,CURLOPT_USERPWD,$USER_NAME.":".$PASSWORD);curl_setopt($ch,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);$response=curl_exec($ch);if($response===FALSE){die(curl_error($ch));}curl_close($ch);return$response;}
<?phpheader("Content-type: text/html; charset=UTF-8");// Case of this path, in the same directory there is a JSON file.$json=@file_get_contents('./entrylist.json',true);if($json===false){die('error');}else{$data=json_decode($json,true);$value=array_rand_value($data);foreach($valueas$key=>$val){$title=$val['title'];$href=$val['permalink'];}$out='<p class="randEntry"><a href="'.$href.'">'.$title.'</a></p>';print$out;}/*/ lib from Qiita http://qiita.com/Kazuhiro15/items/01d5692950c5fd8dc2a3/ http://qiita.com/Kazuhiro15/items/01d5692950c5fd8dc2a3#comment-b4c14342ee0cb2908fbf*/functionarray_rand_value($array,$num=1){if($num<1){return;}if($num>=count($array)){return$array;}returnarray_intersect_key($array,array_flip((array)array_rand($array,$num)));}
Comments (0)
HTTPSSSH
You can clone a snippet to your computer for local editing.
Learn more.