JSON to PHP
Generate PHP 8 classes from a JSON sample, using promoted readonly constructor properties and a fromArray() factory — or switch to array literal mode to get the data itself as PHP source, handy for fixtures and config files.
How to generate PHP classes from JSON
- Paste a JSON sample — ideally an array of several records, so optional fields are detected.
- Set the Root type name. Nested objects are named after the key that holds them, singularised for arrays.
- Choose Typed classes for a model, or Array literal to embed the data in PHP source.
- Set a Namespace if the file belongs in an autoloaded tree.
- Copy the code, or download it as a file.
Type mapping
- Integers →
int; fractional →float; booleans →bool; strings →string. - Arrays →
array, with a@var T[]docblock, since PHP has no generic array type. Static analysers such as PHPStan and Psalm read the docblock. - Objects → a named class.
- null / mixed →
mixed. - Optional fields → nullable type with a
= nulldefault.
Getting good types out of a sample
Type inference from a sample is only as good as the sample. Three habits make the output far more useful:
- Paste an array, not one record. When you pass several records, a key missing from any of them is marked optional and a field that is sometimes a number and sometimes a float widens to a float. One record makes everything look required.
- Include the awkward cases. A record with a null, an empty array, and a missing optional key teaches the generator more than ten identical happy-path records.
- Check unions by hand. A field that holds different shapes in different records falls back to the language's "any" type. That is a signal your data has a variant the generator cannot express — model it explicitly.
Privacy
Nothing is uploaded. Inference and code generation run in this tab. No server sees the payload you paste — which matters, because real API responses tend to contain real user data.
FAQ
Which PHP version do I need?
Constructor property promotion needs PHP 8.0, readonly needs 8.1. Tick No readonly to target 8.0. For 7.x you would need explicit properties and a hand-written constructor.
Why readonly by default?
A model built from a JSON response is a value object — mutating it after construction almost always signals a bug. readonly makes that a compile-time error rather than a debugging session.
Does fromArray recurse into nested objects?
Yes, for object-typed fields it calls the nested class's own fromArray. Arrays of objects are left as plain arrays — map them yourself, since the element type is only known from the docblock.