乐闻世界logo
搜索文章和话题

How to remove HTTP headers from CURL response?

1个答案

1

In HTTP requests using CURL, server responses typically include HTTP headers and the actual content (such as HTML, JSON, etc.). If we are only concerned with the content portion, removing HTTP headers from CURL responses is highly beneficial. This can be achieved by configuring CURL options.

Implementation Steps:

  1. Set CURL options to return response: Using the CURLOPT_RETURNTRANSFER option allows CURL to return the response content as a string instead of directly outputting it. This enables us to process the string manually.

    php
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  2. Disable header output: By setting CURLOPT_HEADER to 0 or false, we can prevent CURL from outputting the response headers.

    php
    curl_setopt($ch, CURLOPT_HEADER, 0);

Complete code example:

Suppose we want to retrieve JSON data from an API, using PHP as an example:

php
<?php // Initialize CURL session $ch = curl_init(); // Set CURL options curl_setopt($ch, CURLOPT_URL, "http://example.com/api/data"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); // Execute CURL session $response = curl_exec($ch); // Check for errors if(curl_errno($ch)) { echo 'Curl error: ' . curl_error($ch); } // Close resource curl_close($ch); // Output result echo $response; ?>

In this code snippet, setting CURLOPT_RETURNTRANSFER to 1 causes CURL to return the execution result to the variable $response, and setting CURLOPT_HEADER to 0 ensures that HTTP headers are not included in the returned content.

In summary, by correctly configuring CURL options, it is straightforward to exclude HTTP header information from the response, making data processing simpler and clearer.

2024年8月13日 22:37 回复

你的答案