0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

curlのレスポンスをheaderとbodyで分けて取得する

Posted at

外部APIにてレスポンスにてheaderから取得する場合があったので、備忘録として残します。
他何かいい方法あればです。


$url = 'https://****.com';
$headers =  array("Content-Type: application/json");
$post_data = json_encode([1 => 'a']);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // curl_exec() 経由で応答データを直接取得できる
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

// headerとbodyを取得
$header = substr($result, 0, $info["header_size"]);
$header = $this->get_result_header($header);
$body = substr($result, $info["header_size"]);

private function get_result_header ($header) {
    $_header = str_replace("\r", '', $header);
    $tmp_header = explode("\n", $_header);
    $res = array();
    foreach ($tmp_header as $row_data) {
        $tmp = explode(': ', $row_data);
        $key = trim($tmp[0]);
        if ( $key == '' ) {
            continue;
        }
        $val = str_replace($key.': ', '', $row_data);
        $res[$key] = trim($val);
    }
    return $res;
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?