0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHP+cURLで、Qiitaに記事を投稿するプログラム

Posted at

PHPで、Qiitaに記事を投稿したく、いろいろな記事を参照していたのですが、こちらの参考記事がそのままではうまく動作しませんでした。

あれこれ試行錯誤したらできました。以下、はまりやすいポイントとともに。

SSLでの通信にする必要がある

記事では http://qiita.com/api/v2/itemsにアクセスしている例があるのですが、いつからなのか https でなければ投稿ができないようでした。

Windowsの PHPで、SSLに cURLでアクセスするには証明書が必要

https にアクセスすると、次のようなエラーメッセージが表示されます。

SSL certificate problem: unable to get local issuer certificate

原因としては、証明書が存在しないためだそうで、php.inicurl.cainfo に、証明書(.crt)ファイルを指定する必要があります。筆者の場合は、別途インストールしていた Gitに内蔵されていた証明書を指定して凌ぎました。

curl.cainfo = c:\Program Files\Git\usr\ssl\certs\ca-bundle.crt

tagsの指定方法が変更され、Versionの指定ができるように

結果的に、これは投稿の成否とは関係なかったのですが、tagsには Versionsが指定できるようです。これがないから投稿ができないのかと思ったのですが、結果的には不要だったようです。

書き方としては以下の通り。タグのバージョンとはなんでしょう・・

    'tags' => array(array("name"=>"Ruby", "versions"=>array("0.0.1"))) //タグ

これでようやく投稿ができるようになりました。プログラム全文は以下。

<?php
$json = [
    'title' => 'テストです', //タイトル
    'body' => '#markdown', //本文
    'private' => true, //限定公開か否か
    'tags' => array(array("name"=>"Qiita", "versions"=>array("0.0.1"))) //タグ
];
$curl = curl_init('https://qiita.com/api/v2/items');

$option = [
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS =>json_encode($json),
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer 1ee5ae2f694640a395d35dd7f71bfa24aaba2605', //アクセストークン
        'Content-Type: application/json',
    ],
];
curl_setopt_array($curl, $option);
$result = curl_exec($curl);
$errno = curl_errno($curl);
$error = curl_error($curl);

curl_close($curl);
var_dump($result);
0
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?