見出し画像

PHP|「noto」と「自サイト」の連動

こんにちは。フリーランスのWeBうぇぶやさんです。note歴1ヶ月、起業3ヶ月目の新参者です。「noteに投稿した記事が自サイトにも反映されたらいいな」と思いつき、プログラムを書きました。noteも自サイトも一石二鳥で充実したらいいですよね。


機能

  • noteに投稿した記事に自サイト独自のタグ付けをし分類する。

  • noteに投稿した記事に自サイト独自の表示優先順位を付ける。

  • 自サイト内では表示件数もカスタマイズする。


プログラミングメモ

  function __construct() {
    parent::__construct();

    $this->noteAccount = "_sukiru"; /* noteのアカウント名 */
    $this->noteRequestUrl = "https://note.com/api/v2/creators/$this->noteAccount/contents?kind=note&page=1";
    $this->connectNote();
  }

アカウント名を設定すれば、上記の「noteRequestUrl」より取得可能です。

function connectNote() {
    $this->noteObj = json_decode(file_get_contents($this->noteRequestUrl, false));
    $this->noteContents = $this->noteObj->data->contents;

    foreach ($this->noteContents as $val) {
      $imgFile = $this->genImgFileName($val->eyecatch, $val->id);
      $noteArr = [
          'id' => $val->id,
          'publishAt' => $val->publishAt,
          'name' => $val->name,
          'noteUrl' => $val->noteUrl,
          'body' => $val->body,
          'eyecatch' => $imgFile];

      $indexId = $this->checkDuplicate('note', 'id', $val->id, 'indexId');
      $this->saveImg('note', $imgFile, $val->eyecatch);

      if ($indexId) {
        $this->updateNoteExe($indexId['indexId'], $noteArr);
      } else {
        $this->addNoteExe($noteArr);
      }
    }
  }

自サイトで必要なnoteデータの属性は6種でした。

  • id (例:57653197)

  • publishAt (例:2022-12-01T12:57:44+09:00)

  • name (投稿記事のタイトル)

  • noteUrl (例:https://note.com/_sukiru/n/n4483fb69ac48

  • body (例:本文の一部)

  • eyecatch (例:タイトル画像のURL)

genImgFileName関数でタイトル画像のファイル名を「id」にして、saveImg関数で自サーバーに保存しています。checkDuplicate関数で新規か更新かの判別をしています。関数はいずれもオリジナルです。

別途、タグ付けや表示順を設定しています。


結果

「WeBやさん|note(ブログ)」をご確認ください。連動できました!

WeBやさんはフリーランスとして各種WeBサービスを展開しています。ご興味がございましたらお気軽にお問い合わせください。

この記事が気に入ったらサポートをしてみませんか?