In PHP development, developers often need to fetch data from other servers, such as calling APIs or retrieving remote content. The cURL (Client URL) extension provides a powerful set of tools for handling such network communications. Among them, the curl_multi_getcontent() function is used to obtain the response content from multiple executed cURL sessions.
The main purpose of the curl_multi_getcontent() function is to extract the response content from multiple cURL sessions created with curl_multi_init(). After executing these sessions with curl_multi_exec(), this function retrieves the returned data from each handle. Its usage is straightforward — simply pass in the cURL resource handle you want to retrieve data from.
// Initialize cURL sessions
$ch1 = curl_init('http://www.example.com/api1');
$ch2 = curl_init('http://www.example.com/api2');
// Create a new multi cURL handle
$mh = curl_multi_init();
// Add the sessions to the multi handle
curl_multi_add_handle($mh, $ch1);
curl_multi_add_handle($mh, $ch2);
// Execute all cURL handles
do {
$status = curl_multi_exec($mh, $active);
} while ($status === CURLM_CALL_MULTI_PERFORM || $active);
// Retrieve the content from each session
$contents = array();
foreach([$ch1, $ch2] as $ch) {
$content = curl_multi_getcontent($ch);
$contents[] = $content;
}
// Close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);
// Output the retrieved content
var_dump($contents);
In the example above, two cURL sessions are initialized using curl_init() and then added to a multi cURL handle created with curl_multi_init(). The curl_multi_exec() function executes these sessions concurrently.
After execution, curl_multi_getcontent() retrieves the response content of each session and stores the results in an array. Finally, curl_multi_remove_handle() and curl_multi_close() are used to properly close all sessions and release system resources.
Before calling curl_multi_getcontent(), make sure that each session has been completely executed. Calling the function before the sessions finish may result in incomplete or empty responses.
The curl_multi_getcontent() function is extremely useful when working with concurrent requests. It allows developers to send multiple API calls simultaneously and efficiently retrieve all responses. This makes it an ideal choice for scenarios like batch data fetching, API aggregation, or other high-concurrency network operations.