I wrote the code below to split up a fullname from a .csv file into a first name, middle name, and last name. It works well and gives the following kind of output:
Eric,T.,Nolan
Mary,,Worth
Jim,T.,Lane
E.,Thomas,Powell
William,Reilly,Smith
Johnny,,Depp
Stevie,de,la Soul
I can get it to print to the screen, but need help putting it back in a new .csv file with three fields separated by commas (i.e., firstname, middlename, lastname). Not sure if I should use fwrite or fputcsv. Took me a long time just to split the name and now I'm stuck on writing it back to a new csv file. I'd appreciate some help from the gurus. Thanks all!
Here's my code:
<?php
$file = fopen('nameFile.csv', 'r');
$row = 0;
while (($line = fgetcsv($file)) !== FALSE)
{
list($name[]) = $line;
$row++;
}
$number_of_rows = $row;
fclose($file);
for($i = 0; $i < $number_of_rows; $i++) {
foreach ($name as $NameSplit)
list($first[], $middle[], $last[]) = explode(' ', $NameSplit, 3);
if ( !$last[$i] ) {
$last[$i] = $middle[$i];
unset($middle[$i]);
}
echo $first[$i] . "," . $middle[$i] . "," . $last[$i] . "<br>\n";
}
?>