file_get_contentsで、外部のXMLや画像、webページなどを取得できる
◎普通に取得する場合
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
◎ファイルの一部の読み込み
// 21 文字目から 14 文字ぶん読み込みます
$section = file_get_contents('./people.txt', NULL, NULL, 20, 14);
var_dump($section);
◎Basic認証
file_get_contents("http://user:password@www.example.com/");
◎ストリームコンテキストの使用
・ストリームコンテキストでのBasic認証
// ストリームを作成します
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Authorization: Basic " .base64_encode("user:password"). "\r\n"
)
// 上で設定した HTTP ヘッダを使用してファイルをオープンします
$file = file_get_contents('http://www.example.com/', false, stream_context_create($opts));
・特定のヘッダで送信
// ストリームを作成します
$header = Array(
"Content-Type: application/x-www-form-urlencoded",
"User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)",
"Accept-language: en",
"Cookie: foo=bar"
);
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>join("\r\n", $header),
)
);
$context = stream_context_create($opts);
// 上で設定した HTTP ヘッダを使用してファイルをオープンします
$file = file_get_contents('http://www.example.com/', false, $context);
◎POSTで送信
$data = array(
'param1' => 'hoge',
'param2' => 'hogehoge',
);
$opt = array('http' => array(
'method' => 'POST',
'content' => http_build_query($data),
));
$contents = file_get_contents('http://www.example.com/', false, stream_context_create($opt));