What are the best practices for measuring and optimizing the loading time of external URLs in PHP?

Measuring and optimizing the loading time of external URLs in PHP can be done by using cURL to fetch the content of the URL and measuring the time it takes to complete the request. To optimize the loading time, you can use techniques such as caching the response or using asynchronous requests.

// Measure the loading time of an external URL using cURL
function measureLoadingTime($url) {
    $start = microtime(true);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    
    $end = microtime(true);
    $loadingTime = $end - $start;
    
    curl_close($ch);
    
    return $loadingTime;
}

// Example usage
$url = 'https://www.example.com';
$loadingTime = measureLoadingTime($url);
echo "Loading time for $url: $loadingTime seconds";