PHP Sérialisé vers CSV
Convertissez les données PHP sérialisées en CSV avec aplatissement dot-path
PHP Serialized to CSV: Extracting Tabular Data from Legacy PHP Systems
PHP's serialize() function produces a compact string representation of complex data structures —
arrays, objects, nested associative arrays — that has been the default persistence format for millions of
PHP applications since the early 2000s. When these legacy systems need to feed data into spreadsheets,
relational databases, business intelligence platforms, or data analysis pipelines, the serialized format
becomes a barrier. CSV (Comma-Separated Values) is the universal tabular interchange format understood by
every spreadsheet application, database import tool, and data science library.
This tool parses PHP serialized strings — particularly arrays of associative arrays or objects with consistent keys — and converts them into well-formed CSV output. It extracts field names from array keys to produce column headers, then outputs each element as a row of values. The result is ready for direct import into Excel, Google Sheets, PostgreSQL, pandas, or any system that consumes tabular data. Unlike converting to JSON (which preserves hierarchy for API consumption) or YAML (which targets configuration management), CSV output is specifically optimized for flat, row-oriented data analysis and spreadsheet workflows.
Understanding PHP Serialization Format for Tabular Extraction
PHP serialization encodes data types with single-character prefixes followed by values. Understanding this format is essential for reliable CSV extraction. The key types relevant to tabular conversion are:
- Indexed arrays (
a:): Represent ordered collections. An array of associative arrays maps naturally to CSV rows — each inner array becomes a row, and the keys of the first element define column headers. The serialized forma:2:{i:0;a:2:{s:4:"name";s:5:"Alice";s:3:"age";i:30;}i:1;a:2:{s:4:"name";s:3:"Bob";s:3:"age";i:25;}}describes a two-row dataset with "name" and "age" columns. - Associative arrays: Arrays with string keys (
s:N:"key") provide the column names for CSV output. When all elements in an outer array share the same set of keys, the conversion produces a clean, uniform table. Heterogeneous key sets require column superset merging with empty cells for missing values. - Serialized objects (
O:): PHP objects serialize with their class name and property values. For CSV conversion, the class name is typically discarded and properties are treated as columns — equivalent to associative arrays. Private and protected properties include visibility markers in their serialized keys that must be stripped during extraction. - Scalar values: Strings (
s:), integers (i:), floats (d:), booleans (b:), and NULL (N;) map directly to CSV cell values. Strings are quoted if they contain the delimiter character, integers and floats are written as-is, booleans become "true"/"false" or "1"/"0", and NULL becomes an empty cell. - Nested structures: When a field value is itself an array or object, it cannot be represented as a single CSV cell without serialization. The converter can either serialize nested values as JSON strings within cells, flatten them with dot-notation column names, or skip nested fields entirely depending on the desired output format.
The parser processes the serialized string character by character, building an in-memory representation of the data structure before analyzing its shape for tabular suitability. Arrays of uniform associative arrays produce the cleanest results, while deeply nested or polymorphic structures may require preprocessing or manual field selection before conversion.
Column Header Generation and Data Alignment
The quality of CSV output depends heavily on how column headers are derived from PHP array keys and how rows align when the source data has inconsistent schemas. This tool implements several strategies to produce reliable, well-structured tabular output from real-world PHP serialized data:
- Uniform key extraction: When all elements in the outer array share identical
keys (the most common case for database query results cached via
serialize()), the keys from the first element become column headers in their original order. This produces a header row likeid,username,email,created_atdirectly from the associative array keys. - Superset merging: When elements have different key sets (common in NoSQL-style PHP applications), the converter builds a superset of all keys encountered across all elements. The header row includes every unique key, and rows with missing keys receive empty cells in those positions. Key ordering follows first-encounter order to maintain predictability.
- Object property handling: Serialized PHP objects store properties with visibility
prefixes — public properties use the plain name, protected properties prepend
\0*\0, and private properties prepend\0ClassName\0. The converter strips these prefixes to produce clean column names, converting\0*\0emailto simplyemail. - Numeric key handling: Indexed arrays (integer keys) within an outer associative
array can be converted using positional column names (
col_0,col_1, etc.) or omitted if a header row is not meaningful for the data structure. - Key sanitization: PHP array keys can contain characters that are problematic in CSV headers — commas, quotes, newlines. The converter sanitizes these by replacing special characters with underscores or enclosing the header in quotes per RFC 4180 rules.
Proper column alignment ensures that every row has exactly the same number of fields as the header row. This strict alignment is required for correct parsing by downstream tools — a CSV file with inconsistent field counts will cause import errors in most spreadsheet applications and database bulk loaders.
Common Migration Scenarios from PHP Legacy Systems
PHP serialized data frequently needs CSV conversion during system migrations, data audits, and reporting workflows. These are the most common scenarios where this tool provides immediate value:
- WordPress options and metadata: WordPress stores serialized PHP arrays in the
wp_optionsandwp_postmetatables. Plugin settings, widget configurations, and custom field groups are all serialized. Extracting this data to CSV enables analysis in spreadsheets — identifying unused plugins, auditing configuration drift across environments, or migrating settings to a new platform. - Session data analysis: PHP session files contain serialized user data. Converting session archives to CSV allows security teams to analyze login patterns, track session durations, or audit stored personal data for GDPR compliance. Each session becomes a row with user attributes as columns.
- Cached query results: Many PHP applications cache database query results using
serialize()in file-based or Memcached stores. When migrating away from PHP, these cached datasets need extraction. Converting to CSV provides an intermediate format that any replacement system can ingest. - E-commerce order exports: Legacy PHP e-commerce platforms (Magento 1.x, osCommerce, Zen Cart) store order line items and customer data as serialized arrays. Exporting to CSV enables import into modern platforms, financial reporting tools, or data warehouses.
- Log and audit trail extraction: Applications that logged structured events as serialized PHP arrays can have their logs converted to CSV for analysis with standard tools like Excel pivot tables, SQL queries on imported data, or pandas DataFrames for statistical analysis.
In each scenario, the key advantage of CSV output over other formats is immediate compatibility with non-technical stakeholders' tools. Business analysts, accountants, and project managers can open CSV files directly in their spreadsheet application without any programming knowledge or format-specific tooling — a critical factor when extracting data from developer-oriented legacy systems for business consumption.
CSV Output Configuration and RFC 4180 Compliance
Generating well-formed CSV from PHP serialized data requires careful handling of delimiters, quoting, encoding, and line endings. This tool produces RFC 4180-compliant output by default while offering configuration options for regional and application-specific requirements:
- Delimiter selection: Comma is the default per RFC 4180, but semicolons are standard in European locales where commas serve as decimal separators. Tab-separated output (TSV) is preferred when field values frequently contain commas — common in text-heavy PHP data like blog posts, product descriptions, or user comments.
- Quoting rules: Fields containing the delimiter character, double quotes, or
newlines are enclosed in double quotes. Double quotes within field values are escaped by doubling
them (
""). The tool applies minimal quoting by default (quote only when necessary) but can be configured to quote all fields for maximum compatibility. - NULL and empty value representation: PHP's NULL values (serialized as
N;) become empty cells in CSV output. The tool preserves the distinction between NULL (missing value) and empty string (present but zero-length) — empty strings are quoted as""while NULL produces a truly empty field. - Character encoding: PHP serialized strings store byte lengths, which means multi-byte UTF-8 characters have accurate length annotations. The CSV output preserves UTF-8 encoding and optionally prepends a BOM (Byte Order Mark) for Excel compatibility on Windows.
- Line endings: RFC 4180 specifies CRLF (
\r\n) line endings for maximum compatibility. Unix-only environments may prefer LF (\n) to avoid doubled line breaks in terminal display or version control diffs.
Following RFC 4180 ensures that the generated CSV file can be consumed by any standards-compliant parser without ambiguity. Non-compliant CSV files — missing quotes around delimiter-containing fields, inconsistent line endings, or incorrect escape sequences — cause silent data corruption when imported into databases or spreadsheets, making standards compliance essential for data integrity in migration workflows.
Code Examples
Converting a PHP Serialized Array of Associative Arrays to CSV
// Original PHP code that produced the serialized data:
$users = [
['id' => 1, 'name' => 'Alice Johnson', 'email' => 'alice@example.com', 'role' => 'admin'],
['id' => 2, 'name' => 'Bob Smith', 'email' => 'bob@example.com', 'role' => 'editor'],
['id' => 3, 'name' => 'Carol White', 'email' => 'carol@example.com', 'role' => 'subscriber'],
];
$serialized = serialize($users);
// Output:
// a:3:{i:0;a:4:{s:2:"id";i:1;s:4:"name";s:13:"Alice Johnson";s:5:"email";s:17:"alice@example.com";s:4:"role";s:5:"admin";}i:1;a:4:{s:2:"id";i:2;s:4:"name";s:9:"Bob Smith";s:5:"email";s:15:"bob@example.com";s:4:"role";s:6:"editor";}i:2;a:4:{s:2:"id";i:3;s:4:"name";s:11:"Carol White";s:5:"email";s:17:"carol@example.com";s:4:"role";s:10:"subscriber";}}Output:
id,name,email,role
1,Alice Johnson,alice@example.com,admin
2,Bob Smith,bob@example.com,editor
3,Carol White,carol@example.com,subscriberStandards & Specifications
- RFC 4180 — Common format and MIME type for CSV files — defines quoting, delimiter, and header conventions for the output format
- PHP serialize() Documentation — Official PHP documentation for the serialize function whose output format this tool parses