Tuesday, December 26, 2017

How to create bitly URL using bitly API in PHP?[solved]

Hey All,

Please follow below step to create your long URL to bitly URL as short.
Step1 : Get your long URL form DB as alias
---------------------------------------------------------------------------------------------------
$db     = JFactory::getDbo();
$query  = $db->getQuery(true);
$query->select("id, prod_name, urlalias, bitlyUrl,builderName");
$query->from("#__products");
$query->where($db->quoteName('urlalias').' != "" ' );//http://bit.ly/
$query->where($db->quoteName('bitlyUrl').' ="" OR '.$db->quoteName('bitlyUrl').' = "http://bit.ly/" '  );
$db->setQuery($query);
$resultUrl= $db->loadAssocList();
-----------------------------------------------------------------------------------------------------
$rootURL="https://phptechnicalgroups.blogspot.in"
foreach( $resultUrl as $geturl ){

echo $url = $rootURL.'/'.$geturl['urlalias'];
echo "<br>";
$referralUrl = make_bitly_url($url,'bikashranjan','XXXXXXXXXXXXXX','xml','2.0.1');
echo $sql = "Update ".$db->quoteName('#__products')." SET ".$db->quoteName('bitlyUrl')." = ".$db->quote($referralUrl)." WHERE    ".$db->quoteName('id')." = ".$db->quote($mValue['id']);
echo "<br><br>";
$db->setQuery($sql);
$db->query();
}

Step 2: Create developer account on bit http://dev.bitly.com and get the login user and app key
---------------------------------------------------------------------------------------------------------
//Step 3: Create a function within the function call bitly API follow below function
function make_bitly_url($url,$login,$appkey,$format = 'xml',$version = '2.0.1'){
//create the URL
$bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$appkey.'&format='.$format;
//get the url
//could also use cURL here
$response = file_get_contents($bitly);
//print_r($response);
//parse depending on desired format
if(strtolower($format) == 'json')
{
$json = @json_decode($response,true);
return $json['results'][$url]['shortUrl'];
}
else //xml
{
$xml = simplexml_load_string($response);
return 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
       }
}

Hopefully it will help you :)

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete