In PHP development, we often need to request data from other servers over the network. cURL (Client URL) is a powerful PHP extension library used for network communication in PHP. cURL provides a series of functions, one of which is curl_multi_getcontent()
, which is used to retrieve the content of a cURL session.
The curl_multi_getcontent()
function is designed to obtain the content of multiple cURL sessions created using the curl_multi_init()
function. When using the curl_multi_exec()
function to execute multiple cURL sessions, we can use the curl_multi_getcontent()
function to get the return results of each session. The call to this function is very simple; it only requires passing a cURL resource handle as a parameter.
Below is an example code using the curl_multi_getcontent()
function:
// Initialize cURL sessions
$ch1 = curl_init('http://www.example.com/api1');
$ch2 = curl_init('http://www.example.com/api2');
// Create a new cURL 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 cURL sessions with multiple handles
do {
$status = curl_multi_exec($mh, $active);
} while ($status === CURLM_CALL_MULTI_PERFORM || $active);
// Loop to get the content of each session
$contents = array();
foreach([$ch1, $ch2] as $ch) {
$content = curl_multi_getcontent($ch);
$contents[] = $content;
}
// Close the cURL sessions for multiple 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 code above, we first initialized two cURL sessions using the curl_init()
function and added them to a multi-handle cURL session. Then, we executed these sessions using the curl_multi_exec()
function. During execution, we used the curl_multi_getcontent()
function to retrieve the content of each session and stored the content in an array. Finally, we used the curl_multi_remove_handle()
function and curl_multi_close()
function to close the multiple sessions.
It is important to note that before using the curl_multi_getcontent()
function, we must ensure that the session has completed execution; otherwise, we may not be able to retrieve the content correctly.
In summary, the curl_multi_getcontent()
function is a very useful function that can be used to retrieve the content of multiple cURL sessions. When making concurrent requests to multiple APIs, it can be used to obtain the return results of each session for subsequent processing.