구글 Google URL Shortener API을 php 에서 사용하는 방법을 남김.
사용은 Minilog에서 사용하려는 의도로 Short URL은 별로 내키진 않지만 그래도 공부할겸;;;
우선 PHP 소스
Code Type : php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
function googleShortenUrl( $longUrl )
{
$ch = curl_init();
curl_setopt( $ch , CURLOPT_URL, $googleUrl );
curl_setopt( $ch , CURLOPT_RETURNTRANSFER, true);
curl_setopt( $ch , CURLOPT_SSL_VERIFYPEER, false);
curl_setopt( $ch , CURLOPT_POST, true);
curl_setopt( $ch , CURLOPT_HTTPHEADER, array ( 'Content-Type: application/json' ));
$jsonArray = array ( 'longUrl' => $longUrl );
curl_setopt( $ch , CURLOPT_POSTFIELDS, json_encode( $jsonArray ));
$result = curl_exec( $ch );
curl_close( $ch );
return json_decode( $result , true);
}
function get_url( $str )
{
$homepage_pattern = "" ;
preg_match_all( "/([^\"\'\=\>])(mms|http|HTTP|ftp|FTP|telnet|TELNET)\:\/\/(.[^ \n\<\"\']+)/" , $str , $matches );
return $matches [0];
}
$decodedUrl = googleShortenUrl( $check );
print_r( $check );
print_r( $decodedUrl );
|
위에서 $GOOGLE_API_KEY 에 들어가서 API Key를 받은뒤 넣을것.
그리고 위의 코드를 그대로 쳐 넣으면...
$decodedURL에 저장되고 $decodedURL[id'] 하면 shortURL을 쉽게 구할 수 있음.
일반 문장에서 URL을 찾아내서 그것을 googleShortenUrl로 보내고 고놈이 줄여줌...
리턴은.. 여러개일경우 첫번째 링크만 되는듯;
Array
(
[0] => http://ohyung.net
[1] => http://ohyung.com
)
Array
(
[kind] => urlshortener#url
[id] => http://goo.gl/E8x5C
[longUrl] => http://ohyung.net/
)
실제 Minolog에서 사용한 코드
Code Type : php
1 2 3 |
$contents = $_POST [contents];
$contentsUrl = get_url( $contents );
$contents = str_replace ( $contentsUrl , $decodedUrl [ 'id' ], $contents );
|
이상!