Skip to content

49: Migrate SplFileObject CSV Calls

Write a CSV row and read it back using the standalone CSV functions. PHP 8.6 deprecates the four CSV-specific methods on SplFileObject.

  • PHP 8.6 CLI. Confirm the version with php --version.
  • Review the previous chapter if you’re following the series in order.

Allow about 10 minutes for the walkthrough and exercise.

A runnable splfileobject-csv.php example.

Run the following from the root of the Code with PHP repository.

Terminal window
php code/php-8-6/49-splfileobject-csv/splfileobject-csv.php
splfileobject-csv.php
<?php
declare(strict_types=1);
$stream = fopen('php://temp', 'w+');
if ($stream === false) {
throw new RuntimeException('Cannot open CSV stream');
}
try {
$fields = ['42', 'Dinner, Hobart', 'Said "hello"'];
if (fputcsv($stream, $fields, escape: '') === false || !rewind($stream)) {
throw new RuntimeException('Cannot write and rewind CSV');
}
$row = fgetcsv($stream, escape: '');
echo 'Round trip: ', $fields === $row ? 'yes' : 'no', PHP_EOL;
echo json_encode($row, JSON_THROW_ON_ERROR), PHP_EOL;
} finally {
fclose($stream);
}
Round trip: yes
["42","Dinner, Hobart","Said \"hello\""]

Use fputcsv() and fgetcsv() with a stream resource and pass the CSV controls explicitly. Set an empty escape character for standard doubled-quote escaping. Update readers that previously relied on setCsvControl() or returned those settings with getCsvControl().

Add a field containing a newline. Confirm that the reader returns one logical row with the newline inside the field.

Continue with Replace Deprecated ArrayIterator Methods.