I am working on a CSV parser in PHP.
The parsed $data variable will hold a header row (should be saved as $header) from the submitted file, and the rest of the array (which should be saved into $body array) will hold the actual data.
Is there a concise syntax to split this $data variable into $header and $body?
The code so far is as follows. The CSV file is parsed into a $data array which holds the header and the body data in a single variable.
$csvFile = file($file_name);
$data = [];
foreach ($csvFile as $line) {
// remove unnecessary whitespace characters
$line = str_replace("\xEF\xBB\xBF",'',$line);
$data[] = str_getcsv($line);
}
Edit:
This is the sample CSV data I am working with:
"uid","area","office","tel"
"6936","SEL","Branch 1","080-123-4567"
"6935","SEL","Branch 2","080-123-4567"
"6934","SEL","Branch 3","080-123-4567"
"6933","SEL","Branch 4","080-123-4567"
"6932","SEL","Branch 5","080-123-4567"
"6931","SEL","Branch 6","080-123-4567"
"6930","SEL","Branch 7","080-123-4567"
"6929","SEL","Branch 8","080-123-4567"
"6928","SEL","Branch 9","080-123-4567"
"6927","SEL","Branch 10","080-123-4567"
"6926","SEL","Branch 11","080-123-4567"
The intended results should be as follows:
$data = [
["uid", "area", "office", "tel"],
["6936", "SEL", "Branch 1", "080-123-4567"],
["6935", "SEL", "Branch 2", "080-123-4567"],
["6934", "SEL", "Branch 3", "080-123-4567"],
["6933", "SEL", "Branch 4", "080-123-4567"],
["6932", "SEL", "Branch 5", "080-123-4567"],
["6931", "SEL", "Branch 6", "080-123-4567"],
["6930", "SEL", "Branch 7", "080-123-4567"],
["6929", "SEL", "Branch 8", "080-123-4567"],
["6928", "SEL", "Branch 9", "080-123-4567"],
["6927", "SEL", "Branch 10", "080-123-4567"],
["6926", "SEL", "Branch 11", "080-123-4567"]
]
$header = ["uid", "area", "office", "tel"];
$body = [
["6936", "SEL", "Branch 1", "080-123-4567"],
["6935", "SEL", "Branch 2", "080-123-4567"],
["6934", "SEL", "Branch 3", "080-123-4567"],
["6933", "SEL", "Branch 4", "080-123-4567"],
["6932", "SEL", "Branch 5", "080-123-4567"],
["6931", "SEL", "Branch 6", "080-123-4567"],
["6930", "SEL", "Branch 7", "080-123-4567"],
["6929", "SEL", "Branch 8", "080-123-4567"],
["6928", "SEL", "Branch 9", "080-123-4567"],
["6927", "SEL", "Branch 10", "080-123-4567"],
["6926", "SEL", "Branch 11", "080-123-4567"]
];