[flickr id=”flickrImage_2″ align=”aligncenter” width=”500″ image_author=”Horia Varlan” image_title=”Transparent chemistry glass tubes filled with substances”][/flickr]
Google+の自分の投稿内容(JSON)をPHPで取得して別のサーバーに保存するで取得したデータを、フィード形式に加工して表示します。
APIから出力されるデータ項目はGoogle+の開発者用ドキュメントに解説がありますが、実際のデータをprint_r()
関数で表示して内容を見たほうがわかりやすいかもしれません。
JSONはそのままでは扱いずらいので、json_decode()
関数でオブジェクト化します。
$obj = json_decode($json_data);
オブジェクト化したデータを取り出して、フィード形式に加工していきます。
$str = '<updated>'. $obj->updated. '</updated>';
これもprint_r()
関数で確認しながらだと加工しやすいです。
フィードのフォーマットについてはこちらを参考に。
function change_gdata_to_feed($obj) {
global $user_id; // グローバル変数を関数外から読み込み
$str = ""; // 文字列を格納する変数を定義
$str .= '<?xml version="1.0" encoding="utf-8"?>';
$str .= '<feed xmlns="http://www.w3.org/2005/Atom">';
$str .= '<title>Google+ Public Activity Feed for Kazuma YAGYU</title>';
// JSONからとるのもいいですが、好きなように変更できるのも自作の醍醐味
$str .= '<link href="https://plus.google.com/'. $user_id. '/posts"/>';
$str .= '<id>'. $obj->id. '</id>';
// リンク先をGoogle+のユーザーページにしています
$str .= '<updated>'. $obj->updated. '</updated>';
foreach($obj->items as $entry) { // itemsはループさせます
$str .= '<entry>';
$str .= '<title>'. $entry->title. '</title>';
$str .= '<link href="'. $entry->url. '"/>';
$str .= '<author>';
$str .= '<name>'. $entry->actor->displayName. '</name>';
$str .= '</author>';
$str .= '<summary type="html">'. $entry->object->content. '</summary>';
$str .= '<id>'. $entry->url. '</id>';
$str .= '<published>'. $entry->published. '</published>';
$str .= '<updated>'. $entry->updated. '</updated>';
$str .= '</entry>';
}
$str .= '</feed>';
return $str; // 最後に文字列を格納した変数を返します
}
ひととおりコーディングしたらW3C Feed Validation Serviceでフィードの構文をチェックしましょう。