| 태그 'URL'에 해당되는 글 1건 |
| Google URL Shortener API php curl로 연결해 봅시다. |
Tech - https://ohyung.net/634 (YMD: 11/03/06 21:01)
구글 Google URL Shortener API을 php 에서 사용하는 방법을 남김.

사용은 Minilog에서 사용하려는 의도로 Short URL은 별로 내키진 않지만 그래도 공부할겸;;;

우선 PHP 소스
Code Type : php
function googleShortenUrl($longUrl)
{
    // initialize.
    $ch = curl_init();
    $GOOGLE_API_KEY = "get key https://code.google.com/apis/console";
    $googleUrl = "https://www.googleapis.com/urlshortener/v1/url?key=".$GOOGLE_API_KEY;

    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];
} 

$check= get_url('체크를 해봅시다. http://ohyung.net 으헉이것이 http://ohyung.com 잘될건가?');
$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
$contents = $_POST[contents];
$contentsUrl = get_url($contents);
$contents = str_replace($contentsUrl, $decodedUrl['id'], $contents);

이상!
| 이 포스트에 대한 이용규약 |
Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시 2.0 라이센스 에 따라 이용하실 수 있습니다.
This work is licensed under a Creative Commons Attribution 2.0 Korea LicenseLink in a new window.

| 이 글과 태그로 연관된 글 |

| 트랙백 |
트랙백 주소 :: https://ohyung.net/rserver.php?mode=tb&sl=634