Using curl_multi_getcontent() to Retrieve Content from Multiple cURL Sessions in PHP
curl_multi_getcontent() is a PHP cURL function that retrieves the response content of individual handles within a multi‑handle session, and this guide explains its purpose, usage steps, and provides a complete example demonstrating initialization, execution, content extraction, and cleanup of multiple concurrent requests.
In PHP development, network requests to other servers are often needed, and the cURL extension provides powerful functions for such communication; among them, curl_multi_getcontent() retrieves the content of a cURL session.
The curl_multi_getcontent() function obtains the response data from handles created by curl_multi_init() after they have been executed with curl_multi_exec() . It simply requires the cURL handle resource as its argument.
Below is a complete example demonstrating how to initialize two cURL handles, add them to a multi‑handle, execute them concurrently, fetch each handle’s content with curl_multi_getcontent() , and finally clean up the resources.
<code>// 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 two handles 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;
}
// 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);
</code>The example first creates two individual cURL sessions with curl_init() , adds them to a multi‑handle, runs them with curl_multi_exec() , then uses curl_multi_getcontent() to collect each response into an array before cleaning up with curl_multi_remove_handle() and curl_multi_close() .
It is important to ensure that the multi‑handle execution has finished before calling curl_multi_getcontent() , 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 cURL requests, simplifying the handling of parallel API calls in PHP backend development.
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.