How can PHP utilize multi-threading with cURL to improve the efficiency of retrieving data from multiple servers?

When retrieving data from multiple servers using cURL in PHP, utilizing multi-threading can improve efficiency by allowing multiple requests to be processed simultaneously instead of sequentially. This can significantly reduce the overall time it takes to retrieve data from multiple servers.

<?php

$urls = array(
    'https://example.com/api/data1',
    'https://example.com/api/data2',
    'https://example.com/api/data3'
);

$mh = curl_multi_init();
$handles = array();

foreach ($urls as $url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_multi_add_handle($mh, $ch);
    $handles[] = $ch;
}

$running = null;
do {
    curl_multi_exec($mh, $running);
} while ($running > 0);

foreach ($handles as $handle) {
    $data = curl_multi_getcontent($handle);
    // Process the retrieved data
    echo $data;
    curl_multi_remove_handle($mh, $handle);
}

curl_multi_close($mh);

?>