CSV, JSON and XML Files

5.CSV, JSON and XML Files

M

In this chapter

We'll learn how to write and read CSV files correctly with fputcsv() and fgetcsv() — including quotes, commas and line breaks inside values — how to store JSON files safely and readably, how to read and create XML with SimpleXML and XMLWriter, and which format to choose for which job.

16–18 min

The Problem in Real Life

Olivia's accountant wants the week's bookings as a spreadsheet. Mia builds the lines herself: implode(',', $booking). Excel opens it, and every booking with a note like Wants a "skin fade", short is split across the wrong columns.

The same afternoon, TextFlow starts sending SMS delivery reports — as XML. Mia tries json_decode() on one out of habit and gets null.

M

Every format has rules I didn't know about. I'd rather PHP knew them for me.

Mia

Gluing Strings by Hand vs. Using the Format's Functions

CSV has rules

Commas, quotes and line breaks inside values must be quoted and escaped.

JSON for your own data

Readable, typed, and one function call each way — with the right flags.

XML from partners

Tags, attributes and namespaces, read with SimpleXML or DOM.

CSV, JSON and XML Files

Three formats for data on disk: plain text is rarely enough. Spreadsheets want CSV, your own data is easiest as JSON, and many partners still speak XML. This chapter covers:

  • CSV: writing and reading with fputcsv() and fgetcsv().
  • JSON files: saving and loading structured data safely.
  • XML: reading with SimpleXML, writing with XMLWriter.
  • Choosing a format: which one for which job.

CSV: a CSV file (comma-separated values) is a table in text: one row per line, values separated by commas. The rules get tricky when a value contains a comma, a double quote or a line break: then it must be wrapped in quotes, and quotes inside it doubled — "Wants a ""skin fade"", short". fputcsv($handle, $row) applies every rule for you, and fgetcsv($handle) reads a row back into an array, rules included. Never build CSV with implode() — that's today's bug. The first row usually holds the column names; array_combine($header, $row) turns each row into an associative array.

fputcsv() handles commas, quotes and line breaks
<?php
$bookings = [
[4811, 'Tom Hart', 'Wants a "skin fade", short'],
[4812, 'Ann Lee', "Allergic to hair wax\nPlease use water"],
];
$csv = fopen('php://memory', 'r+');
fputcsv($csv, ['id', 'customer', 'note'], escape: '');
foreach ($bookings as $booking) {
fputcsv($csv, $booking, escape: '');
}
rewind($csv);
echo stream_get_contents($csv);
// id,customer,note
// 4811,"Tom Hart","Wants a ""skin fade"", short"
// 4812,"Ann Lee","Allergic to hair wax
// Please use water"
Reading it back with the header row
<?php
$csv = fopen('php://memory', 'r+');
fwrite($csv, "id,customer,note\n4811,\"Tom Hart\",\"Wants a \"\"skin fade\"\", short\"\n");
rewind($csv);
$header = fgetcsv($csv, escape: '');
while (($row = fgetcsv($csv, escape: '')) !== false) {
$booking = array_combine($header, $row);
echo $booking['customer'], ': ', $booking['note'], "\n";
}
// Tom Hart: Wants a "skin fade", short

The escape argument: fputcsv() and fgetcsv() have an old, PHP-specific $escape argument (a backslash by default) that doesn't follow the CSV standard and can corrupt values ending in a backslash. Since PHP 8.4, leaving it out gives a deprecation ("the $escape parameter must be provided as its default value will change"). Pass escape: '' to switch it off and follow the standard exactly — every example here does. For Excel, two more details: write the bytes "\xEF\xBB\xBF" (a UTF-8 BOM) at the start so accented names like "Lefèvre" display correctly, and remember that some European Excel versions expect ; as the separator (the third argument).

JSON files: for BookBay's own data — bookings, settings — JSON (Act 08 and Act 19) is the natural choice: it keeps types (numbers stay numbers, true stays true), nests, and maps directly to PHP arrays. Save with json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR) — readable, with "Lefèvre" instead of "Lefèvre" — and load with json_decode($json, true, flags: JSON_THROW_ON_ERROR) so a broken file throws (Act 14). Remember that a JSON file is read and written as a whole, which matters as soon as two requests change it at the same time — chapter 6.

A JSON file that's readable and safe
<?php
$file = '/tmp/bookings.json';
$bookings = [['id' => 4811, 'customer' => 'Clare Lefèvre', 'paid' => true, 'url' => '/booking/4811']];
file_put_contents($file, json_encode(
$bookings,
JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR,
));
echo file_get_contents($file), "\n";
$loaded = json_decode(file_get_contents($file), true, flags: JSON_THROW_ON_ERROR);
var_dump($loaded[0]['paid']); // still a real boolean
// [
// {
// "id": 4811,
// "customer": "Clare Lefèvre",
// "paid": true,
// "url": "/booking/4811"
// }
// ]
// bool(true)

XML: XML marks data up with tags (<customer>Tom Hart</customer>) and attributes (<booking id="4811">), and is still common for partners, invoices and feeds. SimpleXML reads it in two lines: simplexml_load_string($xml) or simplexml_load_file($path) returns an object where child tags are properties ($booking->customer) and attributes are array keys ($booking['id']). Values are SimpleXMLElement objects, so cast them: (string), (int). Broken XML returns false with warnings; call libxml_use_internal_errors(true) and read libxml_get_errors() to report problems properly. The PHP Playground doesn't include the XML extensions, so these examples run on your computer; their output below is real.

One booking, three formats

PHP array

['id' => 4811, 'customer' => 'Tom Hart', 'note' => 'Wants a "skin fade", short']

written as

CSV

4811,"Tom Hart","Wants a ""skin fade"", short"

JSON

{"id":4811,"customer":"Tom Hart","note":"Wants a \"skin fade\", short"}

XML

<booking id="4811"><customer>Tom Hart</customer>…</booking>

Reading XML with SimpleXML (run on your computer)
<?php
$xml = <<<XML
<bookings>
<booking id="4811"><customer>Tom Hart</customer><price currency="GBP">2750</price></booking>
<booking id="4812"><customer>Ann &amp; Lee</customer><price currency="GBP">4500</price></booking>
</bookings>
XML;
$root = simplexml_load_string($xml);
foreach ($root->booking as $booking) {
echo (int) $booking['id'], ' ', (string) $booking->customer, ' ',
(int) $booking->price, ' ', $booking->price['currency'], "\n";
}
libxml_use_internal_errors(true);
var_dump(simplexml_load_string('<bookings><booking></bookings>'));
foreach (libxml_get_errors() as $error) {
echo trim($error->message), "\n";
}
// 4811 Tom Hart 2750 GBP
// 4812 Ann & Lee 4500 GBP
// bool(false)
// Opening and ending tag mismatch: booking line 1 and bookings
// Premature end of data in tag bookings line 1

Writing XML: to add a value with SimpleXML, assign it as a property — $booking->customer = 'Sam & Cole'; — which escapes & correctly. The tempting addChild('customer', 'Sam & Cole') does not escape it: PHP warns "unterminated entity reference" and leaves the tag empty. For larger documents, XMLWriter writes element by element, as a stream, and DOMDocument gives full control (the same DOM idea as in JavaScript). One security rule: never enable external entities (LIBXML_NOENT) on XML from outside — that's the XXE attack, and PHP keeps them off by default.

Writing XML: assign properties, or use XMLWriter (run on your computer)
<?php
$root = simplexml_load_string('<bookings/>');
$booking = $root->addChild('booking');
$booking->addAttribute('id', '4813');
$booking->customer = 'Sam & Cole'; // assigning escapes & correctly
echo $root->asXML();
$writer = new XMLWriter();
$writer->openMemory();
$writer->setIndent(true);
$writer->startElement('bookings');
$writer->startElement('booking');
$writer->writeAttribute('id', '4811');
$writer->writeElement('customer', 'Tom Hart');
$writer->endElement();
$writer->endElement();
echo $writer->outputMemory();
// (first an XML declaration line, then:)
// <bookings><booking id="4813"><customer>Sam &amp; Cole</customer></booking></bookings>
// <bookings>
// <booking id="4811">
// <customer>Tom Hart</customer>
// </booking>
// </bookings>

Choosing a format: use CSV for flat tables people open in spreadsheets, JSON for your own structured data and APIs, and XML when a partner or standard requires it. None of them is a database: they don't handle two writers, searching or millions of rows well. The table below compares them.

Table — CSV vs. JSON vs. XML
CSVJSONXML
ShapeFlat tableNested objects and listsNested tags with attributes
Keeps types?No: everything is textYes: numbers, booleans, nullNo: text (schemas can add types)
Read withfgetcsv()json_decode()SimpleXML, DOM, XMLReader
Write withfputcsv()json_encode()SimpleXML, XMLWriter, DOM
Best forSpreadsheets, exportsYour own data, APIsPartners and standards that require it

Key Takeaway

Write CSV with fputcsv() and read it with fgetcsv() — never implode() — so commas, quotes and line breaks inside values are quoted correctly; pass escape: '' (PHP 8.4 deprecates the default) and add a UTF-8 BOM for Excel. JSON suits your own structured data: save with JSON_PRETTY_PRINT, JSON_UNESCAPED_UNICODE and JSON_THROW_ON_ERROR, load with json_decode(..., true, flags: JSON_THROW_ON_ERROR). SimpleXML reads XML as objects — child tags as properties, attributes as array keys, values cast with (string)/(int) — and libxml_use_internal_errors() collects parse errors; assign properties rather than addChild() to escape values, and use XMLWriter or DOM for bigger documents. None of these files replaces a database.

Why This Matters

Exports for accountants, imports from partners and data feeds are part of almost every business application. Using the format's own functions means the file opens correctly everywhere, even when customers type commas, quotes and accents.

These are also the formats you'll exchange with other systems over HTTP in Acts 16 and 19 — the same functions work on API responses as on files.

The accountant's spreadsheet opens cleanly, SMS reports are read with SimpleXML, and bookings are saved as pretty JSON. Then Saturday morning arrives: Tom Hart and Ann Lee both book 10:00 within the same second. Both see "Booked!". Only Ann's booking is in bookings.json. That's the next chapter: locking, atomic writes and temporary files.