hello (visible) world.

foursquareの添付画像を取得する

2012.01.05 · 557 words · 2 minute readPHP

http://4sq.com/〜 という短縮URLから添付された画像を取得する方法など。

元々画像ホスティング(?)サービス的なもの(twitpicとか)には画像だけ取り出せるURLがあったりするんだけど、 foursquare for Developersをザッと読んだ感じでは公式APIとかではできなさそうだったので超やっつけ。

<?php
    $geturl = $_GET['url'];
    $html = file_get_contents($geturl);
    $pattern = '/https:\/\/img-s[.]foursquare[.]com\/pix\/(\w+)[.]jpg/';
    if(preg_match($pattern, $html, $matches)){
        $url = $matches[0];
        header('Content-type: image/jpeg');
        readfile($url);
    }
?>

pic4sq.phpとか適当に名前つけたら

pic4sq.php?url=http://4sq.com/xxxxxx

っという感じで添付された画像が取れる。
img-s.foursquareからは100px四方、300px四方、500px四方の3タイプも取れるっぽいので

<?php
    $geturl = $_GET['url'];
    $html = file_get_contents($geturl);
    
    $pattern = '/https:\/\/img-s[.]foursquare[.]com\/pix\/(\w+)[.]jpg/';
    $replace = 'http://img-s.foursquare.com/derived_pix/$1_100x100.jpg';
    
    if(preg_match($pattern, $html, $matches)){
        $url = $matches[0];
        $pic = preg_replace($pattern, $replace, $url);
        header('Content-type: image/jpeg');
        readfile($pic);
    }
?>

っていう感じにしてあげると100px四方の画像が取れる。
同様に300px、500pxも。

$replace = 'http://img-s.foursquare.com/derived_pix/$1_300x300.jpg';
$replace = 'http://img-s.foursquare.com/derived_pix/$1_500x500.jpg';

にすればいい。

単に画像のURLが欲しければ

    if(preg_match($pattern, $html, $matches)){
        echo $matches[0];
    }

とか

    if(preg_match($pattern, $html, $matches)){
        $url = $matches[0];
        echo $pic = preg_replace($pattern, $replace, $url);
    }

みたいな感じで。
json形式、xml形式で返して欲しかったら適宜応用して。

最初はPHP Simple HTML DOM Parserを使って

    $html = file_get_html($geturl);

    foreach($html->find('img') as $element) {
        if(preg_match($pattern, $element->src, $matches)){
    }

とかやってたけど、preg_match使うならhtmlそのまま取り込めばいいじゃない。ということで。
もっとスマートな方法があったら教えてください。
というか、公式に出来るんだったら早急に教えてください(汗