PHPプログラムに関する各種メモ書き:タグ「URL」での検索

Googleの短縮URLサービスAPI goo.gl をPHPから使用する

Googleの短縮URLサービス goo.gl をPHPから使用するには以下のようなコードで実現できます。

1. APIキー( api_key )を取得する

https://code.google.com/apis/console/

ここから取得できます

2. 以下のPHPコードで実現できます( $api_key に取得したキーをセットすること )

function get_tiny_url($long_url=''){
	$api_url = 'https://www.googleapis.com/urlshortener/v1/url';
	$api_key = 'XXXXXXXXXXX';
	$curl = curl_init("$api_url?key=$api_key");
	curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
	curl_setopt($curl, CURLOPT_POST, 1);
	curl_setopt($curl, CURLOPT_POSTFIELDS, '{"longUrl":"' . $long_url . '"}');
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	$res = curl_exec($curl);
	curl_close($curl);
	$json = json_decode($res);
	$tiny_url = $json->id;
	return $tiny_url;
}

使い方

$long_url = 'http://xxxx.xxxx.xxx.com/xxxxxxxxxxxxxx.html';
$tiny_url = get_tiny_url($long_url);

No.781
04/04 17:46

edit

API
URL

PHPで相対パスから絶対URL(URI)を作成する。または絶対パスを返す。

元となるURLとそれに対する相対パスを指定すると絶対URLを作成する関数です。

元URL:http://www.test.com/gallery/index.html
相対パス:../contact.html
URL:http://www.test.com/contact.html

使い方

$url = make_uri('元url','相対パス');

です。

関数 make_uri

//================ make_uri:version 1.4
function make_uri($base='', $rel_path=''){
    $base = preg_replace('/\/[^\/]+$/','/',$base);
    $parse = parse_url($base);
    if (preg_match('/^https\:\/\//',$rel_path) ){
        return $rel_path;
    }
    elseif ( preg_match('/^\/.+/', $rel_path) ){
        $out = $parse['scheme'].'://'.$parse['host'].$rel_path;
        return $out;
    }
    $tmp = array();
    $a = array();
    $b = array();
    $tmp = preg_split("/\//",$parse['path']);
    foreach ($tmp as $v){
        if ($v){  array_push($a,$v); }
    }
    $b = preg_split("/\//",$rel_path);
    foreach ($b as $v){
        if ( strcmp($v,'')==0 ){ continue; }
        elseif ($v=='.'){}
        elseif($v=='..'){ array_pop($a); }
        else{ array_push($a,$v); }
    }
    $path = join('/',$a);
    $out = $parse['scheme'].'://'.$parse['host'].'/'.$path;
    return $out;
}

元URLと相対パスから絶対パス(ドキュメントルートからのパス表記)を返す関数( make_apath )はこちら。

//============= make_apath:version 1.1
function make_apath($base='', $rel_path=''){
	$base = preg_replace('/\/[^\/]+$/','/',$base);
	$parse = parse_url($base);
	if (preg_match('/^https\:\/\//',$rel_path) ){
		return $rel_path;
	}
	elseif ( preg_match('/^\/.+/', $rel_path) ){
		$out = $parse['scheme'].'://'.$parse['host'].$rel_path;
		return $out;
	}
	$tmp = array();
	$a = array();
	$b = array();
	$tmp = preg_split("/\//",$parse['path']);
	foreach ($tmp as $v){
		if ($v){  array_push($a,$v); }
	}
	$b = preg_split("/\//",$rel_path);
	foreach ($b as $v){
		if ( strcmp($v,'')==0 ){ continue; }
		elseif ($v=='.'){}
		elseif($v=='..'){ array_pop($a); }
		else{ array_push($a,$v); }
	}
	$path = join('/',$a);
	return '/'.$path;
}
No.501
01/21 11:58

edit

URL