Created
March 25, 2020 18:31
-
-
Save mikkame/74be7acd2eccbbcfcd17ab205abbcc8f to your computer and use it in GitHub Desktop.
qiita backup
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// レガシーないいわけ | |
// ひょっとしてcurlない環境でも動けるようにfile_get_contentsベースにしてみる | |
// 古めのPHPでも動くよう配慮してみる | |
if (count($argv) === 1) { | |
echo '第一引数にapi keyを渡してね'; | |
die(); | |
} | |
function apiCall($url){ | |
global $argv; | |
$base_url = 'https://qiita.com'; | |
$opts = [ | |
'http'=> [ | |
'method' => "GET", | |
'header' => "Authorization: Bearer ".$argv[1] | |
] | |
]; | |
$context = stream_context_create($opts); | |
return json_decode(file_get_contents($base_url.$url, false, $context), true); | |
} | |
if (!file_exists('dist')) { | |
mkdir('dist'); | |
} | |
$readme ="generate by Qiita backup tool.\n\n---\n\n"; | |
foreach (range(1, 100) as $p) { | |
$items = apiCall('/api/v2/authenticated_user/items?page='.$p); | |
if (count($items) === 0) { | |
break; | |
} | |
foreach ($items as $item) { | |
if ($items['private']) { | |
continue; | |
} | |
$item_dir = 'dist/'.basename($item['id']); | |
if (!file_exists($item_dir)) { | |
mkdir($item_dir); | |
} | |
$body = $item['body']; | |
$image_count = 0; | |
while(true) { | |
if (preg_match('#(https://qiita-image-stor.+?\.(png|jpg|jpeg|gif))#', $body, $matches)) { | |
$origin_path = $matches[1]; | |
$ext = end(explode('.', $origin_path)); | |
$image_name = $image_count.'.'.$ext; | |
file_put_contents( | |
$item_dir.'/'.basename($image_name), | |
file_get_contents($origin_path) | |
); | |
$body = str_replace($matches[1], './'.$image_name, $body); | |
} else { | |
break; | |
} | |
} | |
$body = $item['title']."\n\n----\n\n".$item['url']."\n\n".$body."\n\n----\n\n".$item['created_at']; | |
file_put_contents($item_dir.'/readme.md', $body ); | |
$readme.="[".$item['title']."](./".$item['id']."/readme.md)\n\n"; | |
} | |
} | |
file_put_contents('dist/readme.md', $readme); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment