ด้านล่างนี้ เป็นตัวอย่าง class ในการเชื่อมต่อ api ด้วย PHP + CURL

class MyURL
{
	private $api_url ='http://api.myurl.la/v1/';
	public $api_key = null;
	
	
	public function shorten($url)
	{
		
		$params['apiKey'] = $this->api_key;
		$params['longURL'] = $url;
		$method = 'shorten/';
		
		$result = $this->curl($params,$method);
		$myurl = json_decode($result, true);
		
		if($myurl['status'] == 'success')
		{
			return array('status' => TRUE, 'longurl' => $myurl['data']['longURL'], 'shorturl' => $myurl['data']['shortURL'], 'hash' => $myurl['data']['hash'], 'qrcode' => $myurl['data']['qrcode']);

		}else{
			return array('status' => FALSE, 'msgerror' => $myurl['status_msg']);
		}
	}
	
	
	private function curl($params=array(),$method)
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $this->api_url.$method);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$response  = curl_exec($ch);
		curl_close($ch);
		return $response;
	}
	
}

ในการเรียกใช้งาน

$myurl = new MyURL();
$myurl->api_key = 'YOU API KEY';//ใส่ api key ของคุณลงไป


$result = $myurl->shorten('http://www.google.com');
var_dump($result);
echo '<br/>';
echo $result['longurl'].'<br/>';
echo $result['shorturl'].'<br/>';
echo $result['hash'].'<br/>';
echo $result['qrcode'];
Tagged with:
 
Set your Twitter account name in your settings to use the TwitterBar Section.