user101289
user101289

Reputation: 10422

PHP fgetcsv with line ending character

I have an oddly-formatted file I need to parse with PHP. It uses ^ as the field delimiter, and ~ as the end-of-line character. I can easily set the $delimiter param of fgetcsv to ^ to get most of the data. The problem is that fgetcsv doesn't accept an EOL character as a parameter-- so it reads the lines based on line breaks rather than respecting the EOL character.

Is there a way to work around this?

Upvotes: 0

Views: 222

Answers (2)

Niels Keurentjes
Niels Keurentjes

Reputation: 41968

Good old PHP, where people forget how to do stuff manually if there's some half-baked standard function available:

$lines = explode('~', file_get_contents($pathToMyFile));
foreach($lines as $line)
{
  $values = explode('^', $line);
}

Depending on the escape strategy (if ^ or ~ occur in values) you'd have to tweak this a bit.

Upvotes: 1

dave
dave

Reputation: 64707

You could read the file, replace ~ with \n, then use str_getcsv:

$csv = file_get_contents('/path/to/file.csv');
$csv = str_replace('~','\n',$csv);
$csv = str_getcsv($csv, '^');

Upvotes: 0

Related Questions