Easiest Way to Shorten Your Long URL Using bit.ly API Using PHP
bit.ly has become one of the largest URL shortner services out there. This will help you shortening the URL programatically using the bit.ly API. This is ready to use code. All you need is to have the valid bit.ly API which is available free on the bit.ly website.
$url = urlencode($longurl);
$apiuser = “your api username”;
$apikey = “your api key”;
$data = file_get_contents(“http://api.bit.ly/v3/shorten?
login=$apiuser&apiKey=$apikey&longUrl=$longurl&format=xml”);
$objXML = new xml2Array();
$arrOutput = $objXML->parse($data);
$shorturl = $arrOutput[0]['children'][2]['children'][0]['tagData'];
Above code snippet makes the use of XML to Array class which is below.
class xml2Array {
var $arrOutput = array();
var $resParser;
var $strXmlData;
function parse($strInputXML) {
$this->resParser = xml_parser_create ();
xml_set_object($this->resParser,$this);
xml_set_element_handler($this->resParser, “tagOpen”, “tagClosed”);
xml_set_character_data_handler($this->resParser, “tagData”);
$this->strXmlData = xml_parse($this->resParser,$strInputXML );
if(!$this->strXmlData) {
die(sprintf(“XML error: %s at line %d”,
xml_error_string(xml_get_error_code($this->resParser)),
xml_get_current_line_number($this->resParser)));
}
xml_parser_free($this->resParser);
return $this->arrOutput;
}
function tagOpen($parser, $name, $attrs) {
$tag=array(“name”=>$name,”attrs”=>$attrs);
array_push($this->arrOutput,$tag);
}
function tagData($parser, $tagData) {
if(trim($tagData)) {
if(isset($this->arrOutput[count($this->arrOutput)-1]['tagData'])) {
$this->arrOutput[count($this->arrOutput)-1]['tagData'] .= $tagData;
}
else {
$this->arrOutput[count($this->arrOutput)-1]['tagData'] = $tagData;
}
}
}
function tagClosed($parser, $name) {
$this->arrOutput[count($this->arrOutput)-2]['children'][] = $this->arrOutput[count($this->arrOutput)-1];
array_pop($this->arrOutput);
}
}


Recent Comments