You should use output buffering:
ob_start();
// write all your code here
header('Content-Length: ' . ob_get_length());
Output buffering gets flushed implicitly when reaching the end of your script
One thing you could try, I'm not sure about, is to leave off the header()
call and see if PHP automatically sets the Content-Length
for you.
See also: ob_start()
Edit
If you're talking about how PHP does it, it doesn't always write that header; once the output buffer is full it will flush it without setting an explicit length header.
See also: http://php.net/manual/en/outcontrol.configuration.php