Mastering curl_multi_getcontent(): Retrieve Multiple cURL Sessions in PHP
This article explains how the PHP curl_multi_getcontent() function works, demonstrates its use with a complete example for fetching multiple concurrent API responses, and highlights important considerations for ensuring each request has finished before retrieving its content.
In PHP development we often need to request data from other servers, and cURL (Client URL) is a powerful extension for network communication. One of its functions, curl_multi_getcontent(), is used to retrieve the content of a cURL session.
The curl_multi_getcontent() function obtains the content of a handle created by curl_multi_init() after the multi handle has been executed with curl_multi_exec(). It simply requires a cURL resource handle as its argument.
Below is a complete example demonstrating how to use curl_multi_getcontent():
// Initialize two cURL sessions
$ch1 = curl_init('http://www.example.com/api1');
$ch2 = curl_init('http://www.example.com/api2');
// Create a new multi handle
$mh = curl_multi_init();
// Add the two 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 the content of each session
$contents = [];
foreach ([$ch1, $ch2] as $ch) {
$content = curl_multi_getcontent($ch);
$contents[] = $content;
}
// Remove handles and close the multi handle
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);
// Output the retrieved contents
var_dump($contents);In the code above we first initialize two cURL sessions with curl_init(), add them to a multi handle, execute them with curl_multi_exec(), and then use curl_multi_getcontent() inside a loop to fetch each session's response, storing the results in an array. Finally we remove the handles and close the multi handle.
It is important to ensure that a session has completed execution before calling curl_multi_getcontent(); otherwise the function may not return the expected data.
In summary, curl_multi_getcontent() is a very useful function for obtaining the content of multiple concurrent cURL sessions, making it easier to handle the results of parallel API requests.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
