API結果を取得するのに、『file_get_contents』だと、不安になるほど遅い…
jsonのPOSTも出来る『file_get_contents』。かなりご愛用。
しかし『SSL形式』は少し苦手の様子。
でも大概APIって『SSL形式』なので、もう「どっか間違えたかな?』と心配になるレベルで遅い!
そんなときは『cURL』がオススメ!
一度作って試すとわかるけど、笑えるほど早さに差が付く。
もし書き換える場合、どの程度書き換えるか比較するために下記に表示しておく。
自分のために!
例として送るjson内容は下記とする。
$url = "https://exp.com/api"; $params = array( "key" => "111", "text" => "テスト", ); $params = json_encode($params); // json化 $header = array( "Content-Length: ".strlen($params), "Accept: application/json", "Content-Type: application/json", );
file_get_contents版
とにかく重いけども
$context = array(
"http" => array(
"method" => 'POST',
"header" => implode("\r\n", $header),
"content" => $params
)
);
$json_response = file_get_contents($url,false,stream_context_create($context));
print_r($json_response); // json結果
print_r($http_response_header); // header配列
cURL版
書く量は増えるけども、ぐっと早くなる。
$curl = curl_init($url);
$options = array(
// HEADER
CURLOPT_HTTPHEADER =>$header,
// Method
CURLOPT_POST => true, // POST
// body
CURLOPT_POSTFIELDS => $params,
// 変数に保存。これがないと即時出力
CURLOPT_RETURNTRANSFER => true,
// header出力
CURLOPT_HEADER => true,
);
//set options
curl_setopt_array($curl, $options);
// 実行
$response = curl_exec($curl);
// ステータスコード取得
$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
// header & body 取得
$header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); // ヘッダサイズ取得
$header = substr($response, 0, $header_size); // header切出
$header = array_filter(explode("\r\n",$header));
$json = substr($response, $header_size); // body切出
curl_close($curl);
print_r($json_response); // json結果
print_r($header); // header配列

コメント