file_get_contents() で GET リクエストを送る場合の値は URL に持たせる

file_get_contents() で POST を送信することができます。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$url = 'http://local.c-list.net/api/create';
$data = array(
	'keyword' => 'あんぱん18',
	'calorie' => 300,
	'data_type' => 'jsonp',
	'apikey' => '607e771cbf9ceb11c5d30bd838cb8285'
);
$header = Array(
	"Content-Type: application/x-www-form-urlencoded"
);
$options = array('http' => array(
	'method' => 'POST',
	'header'  => implode("\r\n", $header), 
	'content' => http_build_query($data),
));
$contents = file_get_contents($url, false, stream_context_create($options));
echo $contents;

ということは file_get_contents で GET も送信できるのでは無いでしょうか。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$url = 'http://local.c-list.net/api/get';
$data = array(
	'keyword' => 'あんぱん18',
	'calorie' => 300,
	'data_type' => 'xml',
	'apikey' => '607e771cbf9ceb11c5d30bd838cb8285'
);
$header = Array(
	"Content-Type: application/x-www-form-urlencoded",
	"User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
);
$options = array('http' =>
	array(
		'method' => 'GET',
		'header'  => implode("\r\n", $header), 
		'content' => http_build_query($data),
	)
);
$contents = file_get_contents($url, false, stream_context_create($options));
print_r($contents);

しかしこれではできません。Twitter で詳しい方に聞いた所。構造上難しいとのことです。しばらく自分できちんと勉強してみて、もしやるとしたら以下のようなコードになるようです。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$url = 'http://local.c-list.net/api/get';
$data = http_build_query(
	array(
		'keyword' => 'あんぱん18',
		'calorie' => 300,
		'data_type' => 'xml',
		'apikey' => '607e771cbf9ceb11c5d30bd838cb8285'
	)
);
$header = Array(
	"Content-Type: application/x-www-form-urlencoded",
	"User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
);
$options = array('http' =>
	array(
		'method' => 'GET',
		'header'  => implode("\r\n", $header), 
	)
);
$contents = file_get_contents($url . '?' . $data, false, stream_context_create($options));
print_r($contents);

コメント

コメントは受け付けていません。