John Davidson

php - Read all csv files in directory doesn't read lines correctly

0 comments
Message:


I have a script that reads all CSV files in a given directory. The reading is okay, but the output isn't what I'm seeking.


The content of the files is


7,5133606393691467151,000000000000000000
5,-841871172646878578,00000000000000
8,-482903031559659252,000000000000

Desired output


Array (
[0] => Array
(
id: 7
number_1: 5133606393691467151
number_2: 000000000000000000
)
[1] => Array (
id: 5
number_1: -841871172646878578
number_2: 00000000000000
)
[2] => Array (
id: 8
number_1: -482903031559659252
number_2: 000000000000
)
)

This is my code so far


$files = glob("SQLs/*.csv");

foreach($files as $file) {

if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 4096, ",")) !== FALSE) {
foreach ($data as $lineArr) {
list($id[],$number_1[],$number_2[]) = $lineArr;
}
}
fclose($handle);
} else {
echo "Could not open file: " . $file;
}
}

Currently got error 500 when I run it through the browser. If I run it in a console like php example.php >> output.txt got nothing again. The file output.txt is empty.



My Answer:
// Directory where CSV files are located
$directory = 'path/to/directory';

// Get all files in the directory
$files = scandir($directory);

// Loop through each file
foreach ($files as $file) {
// Check if file is a CSV file
if (pathinfo($file, PATHINFO_EXTENSION) == 'csv') {
// Read the CSV file
$csv = array_map('str_getcsv', file($directory . '/' . $file));

// Output the contents of the CSV file
echo "Contents of $file:\n";
print_r($csv);
}
}
?>

Rate this post

4 of 5 based on 3171 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us