You need to write a program that opens a text file, reads data and displays information in the browser.

  1. Create a text file.
    The source text file has the following format:

    21.01.01 / 12:00 / подготовка к сессии
    22.01.01 / 14:00 / сдача сессии
    23.01.01 / 15:00 / гуляй
    ...

  2. Open the file, read the data.
    The data should be displayed in a browser in the form of a table.

  3. When writing a program you need to consider the following exceptions:

    • text file may not be;
    • There may be errors when composing a text file.

================================================= ================
So everything is done except the last point.

 <html> <head> <meta charset="UTF-8"> <title>test (PHP)</title> </head> <body> <?php $fname = '1.txt'; $delim = '/'; if (file_exists($fname) && is_readable($fname)) { $file = file($fname); echo "<table border = '1'> <tr> <th>Дата:</th> <th>Время:</th> <th>Событие:</th> </tr>"; foreach ($file as $item) { $newItem = explode($delim, $item); echo "<tr> <td>$newItem[0]</td> <td>$newItem[1]</td> <td>$newItem[2]</td> </tr>"; } echo '</table>'; } else { echo "File not found!"; } ?> </body> </html> 

How to check file format errors.
That is, if there is an extra "/" in the file or it is not at all, the program should show an error!

  • As I understand it, you just need to check every line $ expression for regular expressions Help to implement, pls - Andrey

1 answer 1

I tried to separate the logic from the presentation.

 <?php function parseRow($s, $delim = '/') { $s = trim($s); $regex = '/^(\d+\.\d+\.\d+)\s*' . preg_quote($delim) . '\s*(\d+:\d+)\s*' . preg_quote($delim) . '\s*(.*)$/'; if (!preg_match($regex, $s, $m)) { return false; } return array($m[1], $m[2], $m[3]); } function loadRows($filename) { if (!file_exists($filename) || !is_readable($fname)) { return null; } $result = array(); $f = fopen($filename, 'r'); while (!feof($f)) { $s = fgets($f); if (!$s) { continue; } $result[] = parseRow($s); } fclose($f); return $result; } $rows = loadRows('1.txt'); ?> <html> <head> <meta charset="UTF-8"> <title>test (PHP)</title> </head> <body> <?php if (!$rows): ?> File not found! <?php else: ?> <table border = "1"> <thead> <tr> <th>Дата:</th> <th>Время:</th> <th>Событие:</th> </tr> </thead> <tbody> <?php foreach ($rows as $row): ?> <tr> <?php if (!$row): ?> <td><?=htmlspecialchars($row[0])?></td> <td><?=htmlspecialchars($row[1])?></td> <td><?=htmlspecialchars($row[2])?></td> <?php else: ?> <td colspan="3">Row error</td> <?php endif ?> </tr> <?php endforeach ?> </tbody> </table> <?php endif ?> </body> </html>