今回のエントリーでは、 TwitterAPI から実際にアクセスする外部リンク先の URL や、ハッシュ、リプライ先を取得してみます。ツイート情報を取得するだけだと、リンクは全て t.co の短縮 URL に置き換わってます。そのため、公式の Twitter のような表示はできません。”ある機能”を使って URL 情報を取得したついでに a タグに変換してリンクを実装してみます。
TwitterAPIとは何か?
TwitterAPI とは、ツイート情報などを取得したり投稿するための API のことです。 URL で直接指定して TwitterAPI を呼び出すことができます。
http://api.twitter.com/1/statuses/user_timeline.xml http://api.twitter.com/statuses/user_timeline.xml
このように呼び出すとユーザのタイムラインを取得できます。「 xml 」を今回指定していますが、「 json 」や「 rss 」なども指定できます。
「 user_timeline 」の他にも色んな取得する方法があります。今回は詳しく記述しませんので、他にどんなやり方があるのか知りたい!という方は dev.twitter.com や、日本語に翻訳した watcher.moe-nifty.com さんのメモ、 TwitterAPIのWiki などを参考にしてみてください。
注意して頂きたいのが TwitterAPI で使える処理はいきなり廃止になることもありえますし、仕様が変更されることもあるということです。現在使用する TwitterAPI のバージョンは 1.0 でも問題ありませんが、 1.1 に置き換わることを宣言しています。アンテナをはっていないと処理が変わったことに気づかず、バグを引き起こすこともあります。
Twitterのタイムライン取得処理をコールする
私のアカウントの最新のツイート情報を 5 件分取得します。
http://api.twitter.com/1/statuses/user_timeline.xml?id=omatoro&count=5&include_entities=true
この時、「 include_entities=true 」という指定を忘れずに行なってください。これが今回のエントリのキモとなります。どうせなので、 PHP の関数化をしておきます。
define("USER_TIMELINE_URL", "http://api.twitter.com/1/statuses/user_timeline.xml");
function getTimelineUrl($_user, $_get_twit_num) {
$result = USER_TIMELINE_URL .
"?id=" . $_user.
"&count=" . $_get_twit_num.
"&include_entities=true";
return $result;
}
これで、アカウント名や取得するツイート数を指定して呼び出せることができるようになります。引数の先頭文字が「 _(アンダーバー) 」になっているのは気にしないでください。引数だと分かりやすくするための慣習みたいなものです。
PHPでツイート情報を扱いやすくする
では、作った関数を用いてツイート情報を取得してみましょう。
$xml = simplexml_load_file(getTimelineUrl("omatoro", 5));
これで xml 形式でツイート情報を取得できました。 PHP では xml 形式のデータをオブジェクトのように扱えるようにするための simplexml_load_file 関数があります。これを使って xml をロードすることで配列として扱えるようになります。 どんな風に情報が取得できているのか見てみましょう。
(int) 2 => object(SimpleXMLElement) {
created_at => 'Fri Oct 12 12:34:02 +0000 2012'
id => '256734470248488960'
text => 'リンクの作成はできた。あとは画像読み込みだな~'
source => 'web'
truncated => 'false'
in_reply_to_status_id => object(SimpleXMLElement) {
}
in_reply_to_user_id => object(SimpleXMLElement) {
}
in_reply_to_screen_name => object(SimpleXMLElement) {
}
user => object(SimpleXMLElement) {
id => '75244126'
name => '岡山智弘'
screen_name => 'omatoro'
location => '福岡'
profile_image_url => 'http://a0.twimg.com/profile_images/1019142336/2009y04m17d_191246234_normal.jpg'
profile_image_url_https => 'https://si0.twimg.com/profile_images/1019142336/2009y04m17d_191246234_normal.jpg'
url => 'http://testcording.com/'
description => 'C++好き。映画好き。漫画好き。
ゲーム好き。アニメ好き。面白いもの好き。
Sass好き。
ツイートを鳥分けるWEBサービス作ってみた toriwake.testcording.com - new!'
protected => 'false'
followers_count => '102'
profile_background_color => 'C0DEED'
profile_text_color => '333333'
profile_link_color => '0084B4'
profile_sidebar_fill_color => 'DDEEF6'
profile_sidebar_border_color => 'C0DEED'
friends_count => '189'
created_at => 'Fri Sep 18 09:52:25 +0000 2009'
favourites_count => '49'
utc_offset => '32400'
time_zone => 'Tokyo'
profile_background_image_url => 'http://a0.twimg.com/images/themes/theme1/bg.png'
profile_background_image_url_https => 'https://si0.twimg.com/images/themes/theme1/bg.png'
profile_background_tile => 'false'
profile_use_background_image => 'true'
geo_enabled => 'false'
verified => 'false'
statuses_count => '2579'
lang => 'ja'
contributors_enabled => 'false'
is_translator => 'false'
listed_count => '5'
default_profile => 'true'
default_profile_image => 'false'
following => object(SimpleXMLElement) {
}
follow_request_sent => object(SimpleXMLElement) {
}
notifications => object(SimpleXMLElement) {
}
}
geo => object(SimpleXMLElement) {
}
coordinates => object(SimpleXMLElement) {
}
place => object(SimpleXMLElement) {
}
contributors => object(SimpleXMLElement) {
}
retweet_count => '0'
favorited => 'false'
retweeted => 'false'
entities => object(SimpleXMLElement) {
user_mentions => object(SimpleXMLElement) {
}
urls => object(SimpleXMLElement) {
}
hashtags => object(SimpleXMLElement) {
}
}
}
このように配列として取得できましたので、あとは URL の情報を抜き出すだけですね。
URL,ハッシュ,リプライ先情報を取得する
先ほど見ていただいた xml の中身の中に「 entities 」というオブジェクトがあります。この中に URL 情報や、リプライ先のユーザ情報、ハッシュ情報などが格納されます。どこにあるかはハイライト表示していますので見てみましょう。
(int) 2 => object(SimpleXMLElement) {
created_at => 'Fri Oct 12 12:34:02 +0000 2012'
id => '256734470248488960'
text => 'リンクの作成はできた。あとは画像読み込みだな~'
source => 'web'
truncated => 'false'
in_reply_to_status_id => object(SimpleXMLElement) {
}
in_reply_to_user_id => object(SimpleXMLElement) {
}
in_reply_to_screen_name => object(SimpleXMLElement) {
}
user => object(SimpleXMLElement) {
id => '75244126'
name => '岡山智弘'
screen_name => 'omatoro'
location => '福岡'
profile_image_url => 'http://a0.twimg.com/profile_images/1019142336/2009y04m17d_191246234_normal.jpg'
profile_image_url_https => 'https://si0.twimg.com/profile_images/1019142336/2009y04m17d_191246234_normal.jpg'
url => 'http://testcording.com/'
description => 'C++好き。映画好き。漫画好き。
ゲーム好き。アニメ好き。面白いもの好き。
Sass好き。
ツイートを鳥分けるWEBサービス作ってみた toriwake.testcording.com - new!'
protected => 'false'
followers_count => '102'
profile_background_color => 'C0DEED'
profile_text_color => '333333'
profile_link_color => '0084B4'
profile_sidebar_fill_color => 'DDEEF6'
profile_sidebar_border_color => 'C0DEED'
friends_count => '189'
created_at => 'Fri Sep 18 09:52:25 +0000 2009'
favourites_count => '49'
utc_offset => '32400'
time_zone => 'Tokyo'
profile_background_image_url => 'http://a0.twimg.com/images/themes/theme1/bg.png'
profile_background_image_url_https => 'https://si0.twimg.com/images/themes/theme1/bg.png'
profile_background_tile => 'false'
profile_use_background_image => 'true'
geo_enabled => 'false'
verified => 'false'
statuses_count => '2579'
lang => 'ja'
contributors_enabled => 'false'
is_translator => 'false'
listed_count => '5'
default_profile => 'true'
default_profile_image => 'false'
following => object(SimpleXMLElement) {
}
follow_request_sent => object(SimpleXMLElement) {
}
notifications => object(SimpleXMLElement) {
}
}
geo => object(SimpleXMLElement) {
}
coordinates => object(SimpleXMLElement) {
}
place => object(SimpleXMLElement) {
}
contributors => object(SimpleXMLElement) {
}
retweet_count => '0'
favorited => 'false'
retweeted => 'false'
entities => object(SimpleXMLElement) {
user_mentions => object(SimpleXMLElement) {
}
urls => object(SimpleXMLElement) {
}
hashtags => object(SimpleXMLElement) {
}
}
}
上記のツイート情報では何も URL やハッシュを指定していないので空となっています。 URL や、ハッシュ、リプライをツイートしていると以下のように entities に値が格納されます。
entities => object(SimpleXMLElement) {
user_mentions => object(SimpleXMLElement) {
user_mention => array(
(int) 0 => object(SimpleXMLElement) {
@attributes => array(
'start' => '0',
'end' => '14'
)
screen_name => 'rokusa_mikann'
name => 'ろくさたん'
id => '164084164'
},
(int) 1 => object(SimpleXMLElement) {
@attributes => array(
'start' => '15',
'end' => '22'
)
screen_name => 'phi_jp'
name => 'phi(ファイ)'
id => '73596365'
}
)
}
urls => object(SimpleXMLElement) {
url => object(SimpleXMLElement) {
@attributes => array(
'start' => '31',
'end' => '51'
)
url => 'http://t.co/XWhGXLY2'
expanded_url => 'http://tmlife.net/programming/programming-ref-book-64.html'
display_url => 'tmlife.net/programming/pr…'
}
}
hashtags => object(SimpleXMLElement) {
}
}
entities を使えば URL 情報を取得できそうです。
リンク部分をaタグに変更する
取得ついでに URL 情報を利用してリンクを作ってみます。わざわざ配列を新しく作るのは面倒なので text をそのまま書き換えてしまいます。まず、ツイート情報を格納した xml 情報から一つ一つのツイート情報を取得します。こんなときは foreach を使うと便利です。
foreach ($xml as $tweet) {
// $tweetはツイートの一つ一つの情報
// $tweet->textでツイート内容を取得できる
}
複数の URL や、複数のリプライ、複数のハッシュと、重複した指定をしているとentities の中身が配列になるので foreach を利用します。
foreach ($xml as $tweet) {
// $tweetはツイートの一つ一つの情報
// $tweet->textでツイート内容を取得できる
if (!empty($tweet->entities->user_mentions)) {
foreach ($tweet->entities->user_mentions as $user) {
// $user->screen_nameでユーザ名取得
}
}
if (!empty($tweet->entities->urls)) {
foreach ($tweet->entities->urls as $url) {
// $url->expanded_urlでリンク先のURL取得
}
}
if (!empty($tweet->entities->hashtags)) {
foreach ($tweet->entities->hashtags as $hash) {
// $hash->textでハッシュ(#抜き)取得
}
}
}
少しうんざりする処理ですが、やっているのは中身を一つ一つ取り出せるようにしているだけです。効率良く値を使いまわす処理も作ることができますが、単純な処理の方が伝えやすいのでこの形にしています。
では本題の文字の置き換えによって URL を a タグに書き換えてみましょう。は str_replace 関数を使います。尚リプライの処理、ハッシュの処理は削除しています。
foreach ($xml as $tweet) {
// $tweetはツイートの一つ一つの情報
// $tweet->textでツイート内容を取得できる
if (!empty($tweet->entities->urls)) {
foreach ($tweet->entities->urls as $url) {
// $url->expanded_urlでリンク先のURL取得
// 置換する文字を作成
$replace_text =
'<a target="_blank" href="'.$url->expanded_url.'">'.$url->display_url.'</a>';
// 文字を入れ替える
$tweet->text = str_replace($url->url, $replace_text, $tweet->text);
}
}
}
これで公式の Twitter のように省略したリンクを表示した上で、外部へのリンクを表示することができます。このあとはいつも通りツイートの text を表示させたら内容を入れ替えていますのでリンクごと表示してくれますね。
いかがでしたでしょうか。キモとなるのは entities を利用することです。この機能を使えば、 Twitter を利用した WEB サービスも作れちゃいます。是非参考にしてみてください。

1 reply on “Twitterサービス制作者必見!TwitterAPIでURL,ハッシュ,リプライ先を一発で取得する方法”
[…] […]