JSON to PHP Class
Generate PHP classes from a JSON sample.
Overview
Paste a JSON sample and the generator emits PHP classes with typed properties, a constructor, and a fromArray static factory plus a toArray method. Nested objects become their own classes; arrays of objects become typed arrays with PHPDoc annotations.
It's for PHP developers consuming JSON APIs, hand-rolling DTOs without a heavy serialisation library, or scaffolding models for a Laravel project. Reach for it when building an SDK wrapper around a third-party API, prototyping a microservice client, or cleaning up legacy code that passes associative arrays everywhere.
How it works
The generator walks the JSON tree and produces a class per object with typed properties (PHP 8.1+ syntax: public readonly int $id). Field names are camelCased; original snake_case keys are remembered in the fromArray/toArray pair so JSON round-trips correctly.
Type inference follows JSON's type system: numbers become int or float based on whether they're integral, booleans become bool, strings become string, arrays become array with a PHPDoc @var Item[] hint, and null values widen the type to nullable (?int).
Examples
- Input:
Output:{"id": 1, "name": "Alex", "is_active": true}final class User { public function __construct( public readonly int $id, public readonly string $name, public readonly bool $isActive, ) {} public static function fromArray(array $data): self { return new self( id: $data['id'], name: $data['name'], isActive: $data['is_active'], ); } } - Arrays of objects use PHPDoc:
/** @param Item[] $items */ - Nullable field:
public readonly ?string $note - Nested object -> separate class file recommendation.
FAQ
Does it target a specific PHP version?
Output assumes PHP 8.1+ (readonly properties, constructor property promotion, named arguments). For older versions, manually rewrite to private properties + getters.
Why readonly?
DTOs are usually immutable. Drop readonly if you need mutability after construction.
How does it handle dates?
ISO 8601 strings stay as string. Add a DateTimeImmutable::createFromFormat call in fromArray if you want typed datetimes.
Will the generated code work with Laravel?
Yes - the classes are plain PHP and integrate fine with Laravel. For Eloquent models you'd want a different shape; this generator targets DTOs.