How can PHP be used to read and copy specific lines from a CSV file into a new file?
To read and copy specific lines from a CSV file into a new file using PHP, you can use the fopen function to open the CSV file, read its contents line by line, and then write the specific lines to a new file. You can use functions like fgetcsv to parse the CSV file and determine which lines to copy based on certain conditions.
$sourceFile = 'source.csv';
$destinationFile = 'destination.csv';
$linesToCopy = [2, 5, 7]; // Specify the line numbers to copy
$source = fopen($sourceFile, 'r');
$destination = fopen($destinationFile, 'w');
if ($source && $destination) {
$lineNumber = 1;
while (($data = fgetcsv($source)) !== false) {
if (in_array($lineNumber, $linesToCopy)) {
fputcsv($destination, $data);
}
$lineNumber++;
}
fclose($source);
fclose($destination);
echo 'Specific lines copied successfully.';
} else {
echo 'Error opening files.';
}