We all know about the URL shortening service offered by many websites. Most notable among them is tinyurl.com. There are also other free URL shortening services available on the Internet.
In this post, I will show you how to generate a short URL link to any URL from a PHP script using the short.ie URL shortening service. The actual code is only about ten lines. We will make use of the Zend_Http_Client component of the Zend Framework.
Let's begin coding. Create the file Shorten.php and paste the below lines of code to it.
Require_once the Zend_Http_Client.php file in your script.
* @file Shorten.php
* We assume you have copied the library/Zend directory to the current working directory
* Make sure you include the correct path
Assign the URL that has to be shortened to the variable $myUrl. We insert our URL to the short.ie/api URL.
* The URL that has to be shortened
$myUrl = 'http://example.com/very/long/url/here';
$url = 'http://short.ie/api?url=' . $myUrl . '&format=xml';
Instantiate the Zend_Http_Client object and pass our $url to its constructor. And then send the HTTP request.
$client = new Zend_Http_Client($url);
$response = $client->request();
$xmlString = $response->getBody();
We have the XML string returned by short.ie assigned to $xmlString. It is time to extract the shortened URL from the response object. We use the PHP SimpleXML extension to extract the information from the XML string.
$xml = new simpleXMLElement($xmlString);
echo "The shortened url is " . $xml->shortened . "\n";
I have attached the script so that you can download and play with it.