Skip to content
PHP Logo

How can the PHP League CSV library be utilized to address line ending issues in PHP?

The PHP League CSV library can be utilized to address line ending issues in PHP by specifying the line ending character when reading or writing CSV files. This can help ensure that CSV files are properly formatted regardless of the platform they are being used on.

php
use League\Csv\Reader;
use League\Csv\Writer;

// Specify line ending character when reading CSV file
$csv = Reader::createFromPath('/path/to/file.csv', 'r');
$csv->setDelimiter(',');
$csv->setEnclosure('"');
$csv->setEscape('\\');
$csv->setNewline("\r\n"); // Specify line ending character here

// Specify line ending character when writing CSV file
$csv = Writer::createFromPath('/path/to/output.csv', 'w+');
$csv->setDelimiter(',');
$csv->setEnclosure('"');
$csv->setEscape('\\');
$csv->setNewline("\r\n"); // Specify line ending character here

// Read or write CSV file using the specified line ending character