49: Migrate SplFileObject CSV Calls
Overview
Section titled “Overview”Write a CSV row and read it back using the standalone CSV functions. PHP 8.6 deprecates the four CSV-specific methods on SplFileObject.
Prerequisites
Section titled “Prerequisites”- 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.
What You’ll Build
Section titled “What You’ll Build”A runnable splfileobject-csv.php example.
Step 1: Run the example (~5 min)
Section titled “Step 1: Run the example (~5 min)”Run the following from the root of the Code with PHP repository.
php code/php-8-6/49-splfileobject-csv/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);}Expected Result
Section titled “Expected Result”Round trip: yes["42","Dinner, Hobart","Said \"hello\""]Why It Works
Section titled “Why It Works”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().
Exercise
Section titled “Exercise”Add a field containing a newline. Confirm that the reader returns one logical row with the newline inside the field.
Wrap-up
Section titled “Wrap-up”Continue with Replace Deprecated ArrayIterator Methods.