我成功地编写了以下脚本:
<?php
/* make a URL small */
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);
//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;
}
}
//function to get the url of the event!
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
/* usage */
$short = make_bitly_url('http://site.com/viewEvent.php?id=2323232','bitlyuser','bitlyapikey','json');
echo 'The short URL is: '.$short . "<br>";
echo "PATH: ". curPageURL();
// returns: http://bit.ly/11Owun
?>
现在,这段代码可以生成一个简短的url,其中包含传递给它的任何内容。我在我的网站上有一个推特按钮,它是我从推特开发者网站上得到的。它的工作原理是发布当前页面的完整链接……所以不是缩短版。现在我想当按下推特按钮时,它会产生一个简短的url,这样我就可以在我的网站帐户上分享。这是怎么做到的?
谢谢你,
您应该能够将data-url
选项设置为bitly url。例如
<a href="https://twitter.com/share" class="twitter-share-button" data-url="<?php echo make_bitly_url('http://'.$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"],LOGIN,APPKEY); ?>">Tweet</a>