DEV Community

Discussion on: Create PHP Object from JSON Content

Collapse
 
mrbenosborne profile image
Ben Osborne

Hi, I started work on something similar but uses PHP 8 attributes, take a look github.com/mrbenosborne/json-unmar....

<?php

use JSON\Attributes\JSON;
use JSON\Unmarshal;

include '../vendor/autoload.php';
include 'FlightRoute.php';

/**
 * Class Flight
 */
class Flight
{
    #[JSON(field: 'airline')]
    public string $airlineName;

    #[JSON(field: 'aircraft.type')]
    public string $aircraftType;

    #[JSON(field: 'route', type: FlightRoute::class)]
    public array $route;
}

// Create a new flight class
$flight = new Flight();

// Load our JSON data from file
$jsonData = json_decode(file_get_contents('flight.json'), true);

// Unmarshal JSON
Unmarshal::decode($flight, $jsonData);
Enter fullscreen mode Exit fullscreen mode