Created
December 12, 2014 04:02
-
-
Save zry656565/a2eed2568597b39aae6b to your computer and use it in GitHub Desktop.
获取新浪短域名的方法(PHP版)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class ShortUrl { | |
private static function getJson($url) { | |
$ch = curl_init($url); | |
curl_setopt_array( $ch, [ | |
CURLOPT_AUTOREFERER => TRUE, | |
CURLOPT_HEADER => 0, | |
CURLOPT_RETURNTRANSFER => 1, | |
CURLOPT_FOLLOWLOCATION => TRUE, | |
CURLOPT_CONNECTTIMEOUT_MS => 5000, | |
CURLOPT_TIMEOUT_MS => 5000, | |
] ); | |
$data = curl_exec($ch); | |
curl_close($ch); | |
return $data; | |
} | |
public static function generate($longUrl) { | |
$apiKey = '2518432258'; | |
$apiUrl = 'https://api.weibo.com/2/short_url/shorten.json?source=' . $apiKey; | |
if (is_array($longUrl)) { | |
for ($i = 0; $i < count($longUrl); $i++) { | |
$apiUrl .= '&url_long='. urlencode($longUrl[$i]); | |
} | |
$response = self::getJson($apiUrl); | |
$json = json_decode($response); | |
if (!isset($json) || isset($json->error)) return ''; | |
$result = []; | |
foreach ($json->urls as $url) { | |
$result[$url->url_long] = $url->url_short; | |
} | |
return $result; | |
} else if (is_string($longUrl)) { | |
$apiUrl .= '&url_long='. urlencode($longUrl); | |
$response = self::getJson($apiUrl); | |
$json = json_decode($response); | |
if (!isset($json) || isset($json->error)) return ''; | |
return $json->urls[0]->url_short; | |
} else { | |
return ''; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment