PHP Serialized to JSON

Convert PHP serialized payloads to JSON with safe object handling and detailed errors

Converting PHP Serialized Data to JSON: Universal Data Interchange

PHP's serialize() function produces a compact string representation of complex data structures using a proprietary type-prefixed format. While efficient within the PHP ecosystem, this format is opaque and unreadable by non-PHP systems. JSON (JavaScript Object Notation) is the universal interchange format understood by virtually every programming language, API framework, database system, and developer tool in existence. This tool parses PHP serialized strings and produces clean, standards-compliant JSON output — making legacy PHP data accessible to modern polyglot architectures, debugging workflows, and data migration pipelines without requiring a PHP runtime environment.

Understanding PHP Serialization Format

PHP serialization encodes values using single-character type prefixes followed by the data itself. Each type has a distinct syntax that the serializer must parse correctly to reconstruct the original data structure. The format was designed for compact storage and fast deserialization within PHP, not for human readability or cross-language portability:

  • s:length:"value"; — Strings are prefixed with s:, followed by the byte length of the string, then the string value in double quotes. Example: s:5:"hello"; represents the string "hello". The explicit length enables binary-safe storage but makes manual inspection difficult.
  • i:value; — Integers use the i: prefix followed by the numeric value. Example: i:42; represents the integer 42. PHP integers can be negative and are platform-dependent in size (32-bit or 64-bit).
  • d:value; — Doubles (floating-point numbers) use the d: prefix. Example: d:3.14159;. PHP uses IEEE 754 double-precision, and special values like INF and NAN may appear in serialized output.
  • b:0; or b:1; — Booleans are represented as b: followed by 0 (false) or 1 (true). JSON maps these directly to false and true literals.
  • N; — Null is the simplest type: just the literal N; with no additional data. Maps directly to JSON null.
  • a:count:{...} — Arrays (both indexed and associative) use the a: prefix followed by the element count and key-value pairs enclosed in braces. PHP arrays serve double duty as both lists and dictionaries — the converter must determine which JSON type (array or object) is appropriate based on the keys.
  • O:length:"ClassName":count:{...} — Objects include the class name and property count. Since JSON has no class concept, objects are typically converted to plain JSON objects with their properties as keys.

The parser must handle each type correctly, including edge cases like empty strings (s:0:"";), nested arrays, and objects with private or protected properties (which PHP serializes with null-byte prefixed property names). A robust converter strips these PHP-specific artifacts to produce clean JSON.

Type Mapping Between PHP Serialization and JSON

Converting PHP serialized data to JSON requires mapping between two type systems with different capabilities. Most mappings are straightforward, but some PHP types have no direct JSON equivalent and require decisions about how to represent the data:

  • PHP strings → JSON strings: Direct mapping. PHP serialized strings include explicit byte lengths which the converter uses for parsing accuracy, then outputs standard JSON-escaped strings. Unicode characters, control characters, and special sequences are escaped per the JSON specification (RFC 8259).
  • PHP integers → JSON numbers: Direct mapping. PHP integers (both positive and negative) become JSON integers. Very large integers that exceed JavaScript's safe integer range (2^53 - 1) may lose precision when parsed by JavaScript-based consumers.
  • PHP floats → JSON numbers: Direct mapping for finite values. Special float values (INF, -INF, NAN) have no JSON representation — the converter must either output null, a string representation, or raise an error.
  • PHP booleans → JSON booleans: Direct mapping. b:1; becomes true, b:0; becomes false.
  • PHP null → JSON null: Direct mapping. N; becomes null.
  • PHP indexed arrays → JSON arrays: When all keys are sequential integers starting from 0, the PHP array maps to a JSON array. The converter outputs [value1, value2, ...] without keys.
  • PHP associative arrays → JSON objects: When keys are strings or non-sequential integers, the PHP array maps to a JSON object. Each key-value pair becomes a JSON property.
  • PHP objects → JSON objects: Object instances become plain JSON objects. The class name can be preserved as a metadata property (e.g., "__class": "UserProfile") or discarded depending on the use case. Private and protected property visibility markers are stripped.

The critical decision for arrays is determining whether the output should be a JSON array or object. A PHP array with keys [0, 1, 2, 3] is a list and becomes a JSON array. A PHP array with keys ["name", "email", "age"] is a dictionary and becomes a JSON object. Mixed or sparse numeric keys (e.g., [0, 2, 5]) are typically output as JSON objects to preserve the key associations rather than inserting null placeholders.

Why JSON as the Target Format

JSON is the natural first choice when extracting data from PHP serialized strings because of its unmatched ecosystem support and versatility across use cases:

  • Universal language support: Every major programming language has native or standard-library JSON parsing. Python has json, JavaScript has JSON.parse(), Go has encoding/json, Rust has serde_json, Java has Jackson/Gson. PHP serialized data requires custom parsers in every non-PHP language.
  • API integration: JSON is the dominant format for REST APIs, GraphQL responses, and webhook payloads. Converting PHP data to JSON enables direct integration with modern API-driven architectures without intermediate transformations.
  • Database compatibility: PostgreSQL, MySQL, MongoDB, and most modern databases support JSON columns natively. Converted data can be stored directly in JSONB columns with full query and indexing support.
  • Frontend consumption: Browser JavaScript parses JSON natively with zero dependencies. Converting PHP backend data to JSON enables direct consumption by single-page applications, mobile apps, and any JavaScript-based client.
  • Tooling ecosystem: JSON validators, formatters, diff tools, schema validators (JSON Schema), query languages (JSONPath, jq), and visualization tools are abundant. Once data is in JSON format, the entire modern developer toolchain becomes available.
  • Human readability: While more verbose than PHP serialization, JSON is immediately readable by developers. Key-value pairs, nested structures, and array elements are visually clear without needing to decode type prefixes and byte counts.

Compared to other potential target formats, JSON strikes the optimal balance between machine parsability and human readability. It preserves the complete data structure (unlike CSV which flattens hierarchies) while remaining simpler than XML and more universally supported than YAML. For most migration and integration scenarios, JSON is the correct intermediate format.

Common Use Cases and Migration Scenarios

PHP serialized data appears in numerous contexts where legacy PHP applications stored structured data as serialized strings. Understanding these scenarios helps identify when this conversion tool provides the most value:

  • WordPress database migration: WordPress stores plugin settings, widget configurations, and transient data as PHP serialized strings in the wp_options table. Migrating to a non-PHP CMS or headless architecture requires converting this data to JSON for the new system to consume.
  • Session data inspection: PHP session files contain serialized session data. Converting to JSON enables debugging session state, auditing stored user data for compliance (GDPR), or migrating session storage to Redis/Memcached with JSON serialization.
  • Cache store migration: Applications using file-based or database-backed cache with PHP serialization need conversion when migrating to Redis, Memcached, or other cache systems that prefer JSON or MessagePack formats.
  • Legacy API response debugging: Some older PHP APIs return serialized PHP data instead of JSON. Converting the response to JSON makes it parseable by standard debugging tools like Postman, curl with jq, or browser developer tools.
  • Data warehouse ingestion: ETL pipelines extracting data from PHP-backed MySQL databases may encounter serialized columns. Converting to JSON enables processing with standard data engineering tools (Apache Spark, dbt, pandas) without PHP-specific parsers.
  • Cross-platform synchronization: When a PHP system must share data with Node.js, Python, Go, or .NET services, converting serialized data to JSON at the boundary provides a clean, standard interchange format that all parties can consume natively.

In all these scenarios, JSON serves as the bridge between PHP's proprietary serialization and the broader software ecosystem. The conversion is typically a one-time migration step or an ongoing transformation at system boundaries where PHP interacts with non-PHP components.

Code Examples

PHP Serialized Data Converted to JSON Output

// PHP serialized string (output of serialize())
a:3:{s:4:"name";s:11:"Jane Cooper";s:3:"age";i:28;s:7:"address";a:3:{s:6:"street";s:11:"123 Main St";s:4:"city";s:8:"Portland";s:5:"state";s:2:"OR";}}

// Type breakdown:
// a:3:{...}         → Array with 3 elements
// s:4:"name"        → String key, 4 bytes: "name"
// s:11:"Jane Cooper"→ String value, 11 bytes: "Jane Cooper"
// i:28              → Integer value: 28
// a:3:{...}         → Nested array with 3 elements

Output:

{
  "name": "Jane Cooper",
  "age": 28,
  "address": {
    "street": "123 Main St",
    "city": "Portland",
    "state": "OR"
  }
}

PHP Serialized Array with Mixed Types to JSON

// Serialized data with booleans, null, and indexed array
a:5:{s:2:"id";i:1001;s:6:"active";b:1;s:7:"deleted";b:0;s:5:"notes";N;s:4:"tags";a:3:{i:0;s:3:"php";i:1;s:5:"mysql";i:2;s:5:"redis";}}

// Type mapping:
// b:1   → true (boolean)
// b:0   → false (boolean)
// N;    → null
// a:3:{i:0;...;i:1;...;i:2;...} → Sequential keys → JSON array

Output:

{
  "id": 1001,
  "active": true,
  "deleted": false,
  "notes": null,
  "tags": ["php", "mysql", "redis"]
}

Frequently Asked Questions

Do you execute PHP objects?

No. Objects are mapped to safe JSON structures without class instantiation.

Can I export to other formats?

Yes. Use PHP Serialized to CSV and PHP Serialized to YAML.