Use gzgets() when you need to reads a line from a gzip file stream in a PHP application. The examples below show the actual operation and its limitations.
What Is gzgets() in PHP?
Reads a line from a gzip file stream. The exact signature supported by your installation depends on its PHP version and enabled extensions.
Its syntax is:
gzgets($stream, ?int $length = ...): string|false
Parameters and return value: The parameter types, optional arguments, references, and return type are shown in the signature above. Optional parameters are marked with an ellipsis in this reference signature.
Example 1: Basic Usage
<?php
$path = tempnam(sys_get_temp_dir(),"gzip_"); $file = gzopen($path,"wb"); gzwrite($file,"red
blue
"); gzclose($file); $file = gzopen($path,"rb"); echo gzgets($file); gzclose($file); unlink($path);
Output:
red
Example 2: Different Input or Behavior
<?php
$path = tempnam(sys_get_temp_dir(),"gzip_"); $file = gzopen($path,"wb"); gzwrite($file,"one
two
"); gzclose($file); $file = gzopen($path,"rb"); gzgets($file); echo gzgets($file); gzclose($file); unlink($path);
Output:
two
Practical Example: Applying the Function
<?php
$path = tempnam(sys_get_temp_dir(),"gzip_"); $file = gzopen($path,"wb"); gzwrite($file,"A
B
"); gzclose($file); $file = gzopen($path,"rb"); while (($line = gzgets($file)) !== false) echo trim($line) . PHP_EOL; gzclose($file); unlink($path);
Output:
A
B
Important Behavior and Edge Cases
Line endings are retained in returned strings; trim only when desired.
Comparison With Related Functions
| Approach | Difference |
|---|---|
gzgets() | Reads a line from a gzip file stream. |
| Related operation | fgets() reads ordinary file streams; gzgets() reads gzip streams. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring the function-specific limitation | Line endings are retained in returned strings; trim only when desired. |
| Confusing this function with a related operation | fgets() reads ordinary file streams; gzgets() reads gzip streams. |
Key Takeaways
- Reads a line from a gzip file stream.
- Line endings are retained in returned strings; trim only when desired.
- fgets() reads ordinary file streams; gzgets() reads gzip streams.
Use gzgets() for the specific operation demonstrated above. Check its prerequisites and handle failure conditions before using it with production data.