コンテンツにスキップ

PHP/HTTPリクエストとAPI

出典: フリー教科書『ウィキブックス(Wikibooks)』
< PHP

HTTPリクエストとAPI

[編集]

cURLを使用したGETリクエスト

[編集]

外部APIからデータを取得する例です。

<?php
$ch = curl_init('https://api.example.com/data');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);
print_r($data);
?>

cURLを使用したPOSTリクエスト

[編集]

POSTデータを送信する例です。

<?php
$ch = curl_init('https://api.example.com/submit');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, ['name' => 'John', 'age' => 30]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

echo $response;
?>