Backend Development 3 min read

Using curl_multi_getcontent() to Retrieve Content from Multiple cURL Sessions in PHP

This article explains how the PHP curl_multi_getcontent() function retrieves the response of each cURL handle created with curl_multi_init() and executed via curl_multi_exec(), provides a complete example with code, and highlights important usage considerations for concurrent API requests.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using curl_multi_getcontent() to Retrieve Content from Multiple cURL Sessions in PHP

In PHP development, the curl_multi_getcontent() function is used to retrieve the content of a cURL session that was created with curl_multi_init() and executed with curl_multi_exec() .

The function takes a cURL handle as its parameter and returns the response body of that handle after the multi‑handle has finished executing.

Below is an example demonstrating how to initialize two cURL sessions, add them to a multi‑handle, execute them concurrently, and then fetch each response using curl_multi_getcontent() .

// Initialize cURL sessions
$ch1 = curl_init('http://www.example.com/api1');
$ch2 = curl_init('http://www.example.com/api2');

// Create a multi‑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 the multi‑handle
do {
    $status = curl_multi_exec($mh, $active);
} while ($status === CURLM_CALL_MULTI_PERFORM || $active);

// Retrieve each session's content
$contents = array();
foreach([$ch1, $ch2] as $ch) {
    $content = curl_multi_getcontent($ch);
    $contents[] = $content;
}

// Clean up
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

// Output the results
var_dump($contents);

The example shows that before calling curl_multi_getcontent() you must ensure the multi‑handle has completed execution; otherwise the function may not return the expected data.

In summary, curl_multi_getcontent() is a useful function for obtaining the results of multiple concurrent API requests, simplifying post‑processing of each response.

backendhttpPHPAPIcurlMulti
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.