How can the Content-Length header be accurately extracted from multiple headers returned by get_headers() in PHP?

When using the get_headers() function in PHP to retrieve headers from a URL, the Content-Length header may be returned as part of an array along with other headers. To accurately extract the Content-Length header, you can iterate through the array of headers and check for the presence of the Content-Length key. Once found, you can retrieve the value associated with that key.

$url = 'https://www.example.com';
$headers = get_headers($url, 1);

$contentLength = '';
foreach ($headers as $header) {
    if (strpos($header, 'Content-Length') !== false) {
        $contentLength = $header;
        break;
    }
}

echo "Content-Length: " . $contentLength;