Zend PHP 7 Certification – Input/Output – Reading and Writing

This post covers the Reading and Writing section of the Input/Output chapter when studying for the Zend PHP 7 Certification.

PHP contains many functions that help read and write files and file resources. The functions return the read data or FALSE on failure.

The file_get_contents() reads the contents of the file into string.

$contents = file_get_contents("somefile.txt");
echo $contents; // Outputs the file as a string

The file() function reads the contents of the file into an array. Each element of the array corresponds to a line in the file, with the newline still attached. Upon failure, file() returns FALSE.

$contents = file("somefile.txt");
print_r($contents); // Outputs the file as an array

The readfile() function reads a file and writes it to the output buffer. It returns the number of bytes read from the file.

$contents = readfile("somefile.txt");

The fgets() function gets a line from file pointer. This function is usually used when reading a file line by line as the below example represents:

$file = fopen("somefile.txt","r");

while(!feof($file))
{
  echo fgets($file). "<br />";
}

fclose($file);

The fgetss() function is identical to fgets(), except that fgetss() attempts to strip any NULL bytes, HTML and PHP tags from the text it reads.

<?php
$str = <<<EOD
<html><body>
 <p>Welcome! Today is the <?php echo(date('jS')); ?> of <?= date('F'); ?>.</p>
</body></html>
Text outside of the HTML block.
EOD;
file_put_contents('sample.php', $str);

$handle = @fopen("sample.php", "r");
if ($handle) {
    while (!feof($handle)) {
        $buffer = fgetss($handle, 4096);
        echo $buffer;
    }
    fclose($handle);
}

This would output something like:

Welcome! Today is the  of .

Text outside of the HTML block.

The fgetcsv() function is similar to fgets() except that fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read.

array fgetcsv ($handle, $length, $delimiter, $enclosure, $escape)

So to read and print contents of a CSV file, you could write the below.

<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}

The file_put_contents() function writes data to a file. This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.

This function returns the number of bytes that were written to the file, or FALSE on failure.

$file = 'people.txt';
// The new person to add to the file
$person = "John Smith\n";
// Write the contents to the file, 
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);

The fwrite() function writes to a file and returns the number of bytes written.

$fp = fopen('data.txt', 'w');
fwrite($fp, '1');
fwrite($fp, '23');
fclose($fp);

// the content of 'data.txt' is now 123 and not 23!

The fputs() function is an alias of fwrite().

The fputcsv() function formats a line (passed as an array) as CSV and write it (terminated by a newline) to the specified file handle.

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);

$fp = fopen('file.csv', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);

The fprintf() function writes a formatted string to a stream and returns the length of the string written.

if (!($fp = fopen('date.txt', 'w'))) {
    return;
}

fprintf($fp, "%04d-%02d-%02d", $year, $month, $day);

Note: This article is based on PHP version 7.1.