<?php
/**
* Imports data from a text file, performing defensive checks.
*
* @param string $filePath Path to the text file.
* @param string $delimiter Delimiter used in the text file (default: comma).
* @param bool $skipHeader Whether to skip the first line (header) (default: false).
* @return array|false An array of data rows, or false on error.
*/
function importTextFile(string $filePath, string $delimiter = ',', bool $skipHeader = false): array|false
{
if (!file_exists($filePath)) {
error_log("File not found: $filePath");
return false; // File does not exist
}
if (!is_readable($filePath)) {
error_log("File not readable: $filePath");
return false; // File is not readable
}
$data = [];
$headerSkipped = false;
if (($handle = fopen($filePath, 'r')) !== false) {
while (($row = fgetcsv($handle, 0, $delimiter)) !== false) {
if (!$headerSkipped) {
$headerSkipped = true;
continue; // Skip the header row
}
// Defensive check: Ensure row has the expected number of columns.
if (count($row) < 1) {
error_log("Skipping row with insufficient columns: " . implode(',', $row));
continue;
}
//Data validation example - check if a required field is not empty
if (empty($row[0])) {
error_log("Skipping row with empty required field (column 0): " . implode(',', $row));
continue;
}
$data[] = $row;
}
fclose($handle);
} else {
error_log("Failed to open file: $filePath");
return false; // File opening failed
}
return $data;
}
//Example Usage:
// $data = importTextFile('data.txt', ',', true);
// if ($data !== false) {
// print_r($data);
// }
?>
Add your comment