今朝、百度短縮URL APIを利用して短縮URLを生成するチュートリアルとコードを公開しました。その後、CSDNで百度短縮URLを生成する、より優れた方法を見つけたので、こちらに転載して皆さんと共有したいと思います。また、前回の記事のバージョンと比較してみることもできます。とにかく、こちらのほうがより速くて便利で、設計ロジックも非常に綿密だと思います。以下がコード部分です。
PHPコード
<?php
function send_post($url, $post_data) {
$postdata = http_build_query($post_data);
$options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type:application/x-www-form-urlencoded',
'content' => $postdata,
'timeout' => 15 * 60
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
return $result;
}
$post_data = array(
'url' => 'URL'
);
$json_data = send_post('http://dwz.cn/create.php', $post_data);
$arr = json_decode($json_data,true);
echo $arr['tinyurl'];
?>