Building applications using PHP can be both challenging and rewarding. Understanding how to manage transactions, especially when dealing with CSV files, allows developers to efficiently handle data flow in real-time applications. In this article, we will implement a small part of a transaction management application using procedural PHP, focusing on reading, parsing, and displaying transaction data effectively.
Introduction to the Application
The primary goal of our application is to read transaction files from a specified directory, extract the relevant data, and output it in a user-friendly HTML table format. The initial dataset involves a single CSV file, sample1.csv
, which contains various transactions. We will later extend the functionality to include multiple files and different data formats in subsequent sections of our course.
Setting Up the Environment
Before diving into the coding, we need to ensure our PHP environment is set up correctly. We will create three constants that define:
APP_PATH
: The main application directory path.FILES_PATH
: The directory where transaction files are stored.VIEWS_PATH
: The path to the views directory containing the HTML template for displaying transaction data.
Let’s modify the existing index.php
to include these constants and prepare for further functions.
Getting Started with Transaction Files
To begin, we’ll create the function getTransactionFiles()
which will scan the TRANSACTION_FILES
directory for all files. This function will return an array containing the names of the files found. Here’s how:
function getTransactionFiles(string $dirPath): array {
$files = [];
foreach (scandir($dirPath) as $file) {
// Skip directories
if (is_dir($file)) continue;
// Add file to the files array
$files[] = $file;
}
return $files;
}
Reading Transaction Data
Once we have the file names, our next step involves reading the contents of each file. We will implement another function called getTransactions()
that accepts a file path as input:
function getTransactions(string $fileName): array {
if (!file_exists($fileName)) {
trigger_error("File {$fileName} does not exist", E_USER_ERROR);
}
$file = fopen($fileName, 'r');
$transactions = [];
// Skip header line
fgetcsv($file);
while (($transaction = fgetcsv($file)) !== false) {
$transactions[] = $transaction;
}
fclose($file);
return $transactions;
}
Formatting and Displaying the Data
With our transactions read into an array, we need to prepare them for display. Each transaction row needs to be formatted correctly, with amounts displayed in a monetary format. Here’s a simple example of how we might structure our HTML output in transactions.php
:
<table>
<thead>
<tr>
<th>Date</th>
<th>Check Number</th>
<th>Description</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<?php foreach ($transactions as $transaction): ?>
<tr>
<td><?= htmlspecialchars($transaction[0]) ?></td>
<td><?= htmlspecialchars($transaction[1]) ?></td>
<td><?= htmlspecialchars($transaction[2]) ?></td>
<td style="color: <?= ($transaction[3] < 0) ? 'red' : 'green' ?>;">
$<?= number_format(abs($transaction[3]), 2) ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Calculating Totals
Additionally, we need to calculate total income, total expenses, and net total. Here’s how we can achieve this:
function calculateTotals(array $transactions): array {
$totals = ['income' => 0, 'expense' => 0, 'net' => 0];
foreach ($transactions as $transaction) {
$amount = floatval(str_replace(['$', ','], '', $transaction[3]));
if ($amount < 0) {
$totals['expense'] += abs($amount);
} else {
$totals['income'] += $amount;
}
}
$totals['net'] = $totals['income'] - $totals['expense'];
return $totals;
}
Final Touches
To ensure a seamless experience for the user, we’ll format the displayed amounts consistently and allow easy scanning of the data. Considerations for edge cases, like handling different CSV formats or error handling for missing or invalid files, should be planned out in future versions of the application, using object-oriented principles for greater flexibility.
Conclusion
Through this exercise, we’ve built a foundational transaction management system using procedural PHP. This system reads CSV files, processes transactions, and displays them in a neatly formatted HTML table, complete with totals. In future lessons, we aim to refactor our procedural code to incorporate object-oriented practices, which will improve maintainability and scalability.
As you implement this yourself, remember to test thoroughly with varied datasets and consider how you might enhance the application further, such as by adding features for data validation or integration with other data sources. Keep coding and stay creative!