What are the best practices for handling CSV data in PHP, especially when the file extension is TXT?
When handling CSV data in PHP, especially when the file extension is TXT, it's important to properly parse the data and handle any potential formatting issues. One way to do this is by using the fgetcsv function in PHP, which reads a line from an open file and parses it as CSV. Additionally, you may need to specify the delimiter and enclosure characters if they are different from the default values.
$filename = 'data.txt';
$delimiter = ',';
$enclosure = '"';
$header = NULL;
$data = [];
if (($handle = fopen($filename, 'r')) !== FALSE) {
while (($row = fgetcsv($handle, 1000, $delimiter, $enclosure)) !== FALSE) {
if (!$header) {
$header = $row;
} else {
$data[] = array_combine($header, $row);
}
}
fclose($handle);
}
print_r($data);