LoginSignup
1
1

More than 3 years have passed since last update.

PHPではてなブログのAPIで自動投稿する方法。

Posted at

PHPではてなブログのAPIで自動投稿する方法です。

ある書籍を読んでいてはてなブログにAPIがあることを知りましたが
PHPの自動投稿の方法が検索してもあまりがない感じでしたので😌作りました。
(はてなのデベロッパーのヘルプを見て作りましたよ😂)

index.php
<?php

require "./config.php";

function hatena_blog($title = "タイトルです", $content = "本文です", $category = "category")
{

    $username = USERNAME;
    $api_key = APIKEY;

    $name = NAME;
    $draft = DRAFT;

    $nonce = sha1(time() . rand() . getmypid(), true);
    $date = new DateTime();

    $blognow = $date->format("Y-m-d\TH:i:s");
    $digest =  base64_encode(sha1($nonce . $blognow . "Z" . $api_key, true));
    $credentials =
        sprintf(
            "UsernameToken Username=\"%s\",PasswordDigest=\"%s\",Nonce=\"%s\",Created=\"%s\"",
            $username,
            $digest,
            base64_encode($nonce),
            $blognow . "Z"
        );

    $headers  = array(
        "X-WSSE: $credentials",
        "Accept: application/x.atom+xml, application/xml, text/xml, */*"
    );

    $POST_DATA = "<?xml version=\"1.0\" encoding=\"utf-8\"?>
    <entry xmlns=\"http://www.w3.org/2005/Atom\"
           xmlns:app=\"http://www.w3.org/2007/app\">
      <title>$title</title>
      <author><name>$name</name></author>
      <content type=\"text/plain\">
      $content
      </content>
      <updated>$blognow</updated>
      <category term=\"$category\" />
      <app:control>
        <app:draft>$draft</app:draft>
      </app:control>
    </entry>
    ";

    $curl = curl_init("https://blog.hatena.ne.jp/" . USERNAME . "/" . BLOGID . "/atom/entry");
    curl_setopt($curl, CURLOPT_POST, TRUE);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $POST_DATA);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($curl);
    if ($response === false) {
        echo 'Curl error: ' . curl_error($curl);
    }

    curl_close($curl);

    var_dump($response);
}

hatena_blog("テスト投稿","これは本文です","blog");
config.php
<?php
define("USERNAME","taokatoshiaki");
define("APIKEY","xxxxxxx");
define("BLOGID","example.hatenadiary.com");//example.hatenadiary.com
define("NAME","taoka");//ブログ投稿者名
define("DRAFT","no");//yes=下書き, no=投稿
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1