What is PHP ob_get_length() Function?
If you want to get length of the content in the current output buffer, use ob_get_length() function. There might be multiple output buffers in your script like the default output buffers and the output buffers starts by ob_start() function. This function counts content length of the current output buffer.
This length is expressed in bytes. Don’t mess with number of character and number of bytes. A character is not always made up of one byte. Some characters consist of more than one byte (Check example 3).
Syntax:
ob_get_length()
Parameters:
This function has no parameter.
Return Values:
The function returns –
- Length of the output buffer content. (Check example 1 and Example 2).
- False, if buffer is inactive.
Examples:
Example 1:
<?php
echo "Output Buffer Length";
echo "<br />Output buffer's content is '".ob_get_contents()."' And, its length in byte is: ".ob_get_length();
?>
Output:
Output Buffer Length
Output buffer's content is 'Output Buffer Length' And, its length in byte is: 20
Explanation:
When PHP executes the string “Output Buffer Length” in the second line, it is stored in the default Apache output buffer. The ob_get_length() function in line #3 shows the string’s length as 20.
Example 2:
<?php
echo "Languages.";
ob_start();
echo "PHP.";
ob_start();
echo "JAVA.";
echo "<br />Output buffer's content is ".ob_get_contents()." And, its length in byte is: ".ob_get_length();
?>
Output:
Language.PHP.JAVA.
Output buffer's content is JAVA. And, its length of in byte is: 5
Explanation:
After starting the last output buffer at line 5, the only content “JAVA.” is sent to this buffer through line 6. That’s why, line 7, shows the content and length of this string “JAVA.”.
Example 3:
<?php
ob_start();
echo "£";
$length = ob_get_length();
echo "<br />Output buffer's content is ".ob_get_contents()." And, its length
of in byte is: ".ob_get_length();
?>
Output:
£
Output buffer's content is £ And, its length of in byte is: 2
Explanation:
Though £ is one character long, but, it takes 2 bytes. So, ob_get_length() function shows its length 2.
PHP Version Support:
PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8
Summary: PHP ob_get_length() Function
PHP ob_get_length() function is a built-in PHP function and part of the PHP’s Output Control functions. It allows you to know the amount of data stored in the current buffer.