What is the best way to extract specific columns from a CSV file using PHP?
To extract specific columns from a CSV file using PHP, you can read the file line by line and use the `str_getcsv` function to parse each line into an array. Then, you can access the specific columns you need based on their index in the array.
$csvFile = 'data.csv';
$columnsToExtract = [0, 2]; // Columns to extract (0-based index)
$extractedData = [];
if (($handle = fopen($csvFile, 'r')) !== false) {
while (($data = fgetcsv($handle)) !== false) {
$rowData = [];
foreach ($columnsToExtract as $columnIndex) {
$rowData[] = $data[$columnIndex];
}
$extractedData[] = $rowData;
}
fclose($handle);
}
print_r($extractedData);