塩焼きブログ

塩焼きに関しての研究内容を公開しています

Qiitaの記事をMovableType形式でエクスポートする

ポイントはCONVERT BREAKS: markdownってところでした。これをしないとちゃんと記事が展開されない。

<?php
class Qiita {

  const ITEM_LIMIT = 20;

  private $token;

  public function __construct($token) {
    $this->token = $token;
  }

  public function getInfo() {
    return $this->getRequest('https://qiita.com/api/v2/authenticated_user');
  }

  public function getItems($page) {
    return $this->getRequest(
      'https://qiita.com/api/v2/authenticated_user/items?' .
      http_build_query(['page' => $page, 'per_page' => self::ITEM_LIMIT])
    );
  }

  private function getRequest($url) {
    $curl = curl_init($url);
    curl_setopt_array($curl, [
      CURLOPT_CUSTOMREQUEST => 'GET',
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . $this->token,
        'Content-Type: application/json',
      ],
    ]);
    $result = curl_exec($curl);
    curl_close($curl);

    return json_decode($result);
  }
}


$token = 'token';
$outputPath = '/home/user/Downloads/qiita.html.txt';

$setouchi = new Qiita($token);
$max = ceil($setouchi->getInfo()->items_count / Qiita::ITEM_LIMIT);

$result = "";

for ($i = 1; $i <= $max; $i++) {

  echo PHP_EOL;

  foreach ($setouchi->getItems($i) as $remoteItem) {
    echo "+";
    $body = "";
    $body .= "AUTHOR: user\n";
    $body .= "TITLE: " . $remoteItem->title . "\n";
    $body .= "BASENAME: " . date("Y/m/d/His", strtotime($remoteItem->created_at)) . "\n";
    $body .= "STATUS: Publish\n";
    $body .= "ALLOW COMMENTS: 1\n";
    $body .= "CONVERT BREAKS: markdown\n";
    $body .= "DATE: " . date("m/d/Y H:i:s", strtotime($remoteItem->created_at)) . "\n";
    $body .= "-----\n";
    $body .= "BODY:\n";
    $body .= $remoteItem->body . "\n";
    $body .= "-----\n";
    $body .= "--------\n";

    $result .= $body;
  }
}

echo PHP_EOL;

file_put_contents($outputPath, $result);