CSV (Comma-Separated Values) is a widely used structured text data format. PHP provides multiple built-in functions to easily read, write, and manipulate CSV files, significantly simplifying development tasks.
$handle = fopen('data.csv', 'r');
while (($row = fgetcsv($handle)) !== FALSE) {
// Process each row of data
}
fclose($handle);
$handle = fopen('data.csv', 'w');
fputcsv($handle, ['col1', 'col2', 'col3']);
fclose($handle);
$row = fgetcsv($handle);
$values = explode(',', $row[0]);
$row = ['col1', 'col2', 'col3'];
$csvLine = implode(',', $row);
To avoid memory overflow in constrained environments, using the generator-based SplFileObject class can efficiently handle large files:
$handle = fopen('data.csv', 'r');
$csv = new SplFileObject('data.csv');
$csv->setFlags(SplFileObject::READ_CSV);
foreach ($csv as $row) {
// Process each row of data
}
Assuming you have a CSV file containing username, email, and password, the following code demonstrates how to read and import the users:
// Open the CSV file
$handle = fopen('users.csv', 'r');
// Skip the header row
fgetcsv($handle);
// Read and process each user record
while (($row = fgetcsv($handle)) !== FALSE) {
$username = $row[0];
$email = $row[1];
$password = $row[2];
// Call your custom function to insert user
insert_user($username, $email, $password);
}
fclose($handle);