Line Filters in PHP

Our line filter program reads input from stdin, processes it, and then prints a derived result to stdout. This example writes a capitalized version of all input text. You can use this pattern to write your own PHP line filters.

<?php

// Wrapping the unbuffered STDIN with a buffered stream gives us a convenient
// fgets() function that reads a line from the input stream.
$stdin = fopen('php://stdin', 'r');

// Read lines from stdin until EOF
while (($line = fgets($stdin)) !== false) {
    // Convert the line to uppercase
    $ucl = strtoupper($line);

    // Write out the uppercased line
    echo $ucl;
}

// Check for errors during reading
if (!feof($stdin)) {
    echo "Error: unexpected fgets() fail\n";
    exit(1);
}

fclose($stdin);

To try out our line filter, first make a file with a few lowercase lines.

$ echo 'hello'   > /tmp/lines
$ echo 'filter' >> /tmp/lines

Then use the line filter to get uppercase lines.

$ cat /tmp/lines | php line-filters.php
HELLO
FILTER

In this PHP version:

  1. We use fopen('php://stdin', 'r') to open a stream for reading from standard input.

  2. We use a while loop with fgets() to read lines from the input stream until we reach the end of the file (EOF).

  3. We use strtoupper() to convert each line to uppercase.

  4. We use echo to print the uppercased line.

  5. After the loop, we check if we’ve reached the end of the file. If not, it means an error occurred during reading.

  6. Finally, we close the input stream with fclose().

This script will behave similarly to the original Go program, reading lines from standard input, converting them to uppercase, and printing the result to standard output.