19
15

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]Twitterのツイート数を取得する方法

Last updated at Posted at 2014-06-08

概要

1.tweet数(を含む文字列)を取得

curlを使ってHTTPリクエストを投げる方法

  • curl_init():初期化(準備)
  • curl_setopt():オプションの設定
  • curl_exec():実行
  • curl_close():セッション終了

HTTPリクエストに使うURLはTwitterのAPI

  • http://urls.api.twitter.com/1/urls/count.json?url=http://foo.bar.jp

(注1)
http://foo.bar.jpの部分は適宜読み替えること。
(注2)
FBいいね数はhttp://graph.facebook.com/http://foo.bar.jpで取得可能。

2.取得した文字列からtweet数のみ抜き出す

preg_replaceを使って文字列置換

  • 正規表現使う
  • 第1引数:pattern。変換前。
  • 第2引数:replacement。変換後。
  • 第3引数:置換させる文字列。

実際に書いたコード

// tweet数(を含む文字列)を取得
$ch = curl_init(); // 初期化
curl_setopt($ch, CURLOPT_URL, "http://urls.api.twitter.com/1/urls/count.json?url=http://foo.bar.jp"); // URLをセット
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // curl_exec()の結果を文字列で返す
$c = curl_exec($ch); // 実行
curl_close($ch); // セッション終了

// 取得した文字列からtweet数のみ抜き出す
$pattern = '/(\D+):(\d+),(.+)/';
$replacement = '$2';
$c = preg_replace($pattern, $replacement, $c);

前半部分(HTTPリクエスト投げる部分)

  • 上記ソースでは、HTTPリクエストにGETメソッドを利用。
  • curl_exec()の行の$cには連想配列を表す「文字列」が入っている。
  • ($cの中身:{"count":226,"url":"http://foo.bar.jp/"})
  • 最終行の$cには「226」が入っている。

後半部分(正規表現使って文字列置換)

  • $patternに代入する値は必ず'//'の間に書く。(おまじない)
  • (\D+)には{"count"が入っている。←「\Dは数値以外」「+は1文字以上」
  • (\d+)には226が入っている。←「\d+は1文字以上の数値」
  • (.+)には"url":"http://foo.bar.jp/"}が入っている。←「.+は任意の1文字以上の文字列」
  • replacement$2は真ん中の(\d+)を表す。
  • $1(\D+)$3(.+)を表す。
19
15
4

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
19
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?