Search by

dcarbone / php-fhir

dcarbone

Tools for creating PHP classes from the HL7 FHIR Specification

Package info

github.com/dcarbone/php-fhir

pkg:composer/dcarbone/php-fhir

Fund package maintenance!

dcarbone

Ko Fi

Statistics

Installs: 326 420

Dependents: 1

Suggesters: 0

Stars: 152

Open Issues: 1

v4.3.1 2026-11-22 04:34 UTC

README

Tools for generating PHP classes from the HL7 FHIR specification.

php-fhir reads the official FHIR XSD schema files and produces a fully-typed PHP library — complete with models for every FHIR type, JSON & XML (de)serialization, validation, and a ready-to-use FHIR REST client. Generated libraries also include a beta cross-version translation API and can optionally include profile classes.

🚀 Just Want the Generated Code?

If you don't need to customise the generation process and just want usable FHIR models in your PHP project, grab the pre-built package:

➡️ dcarbone/php-fhir-generated

That package is kept in sync automatically: every GitHub release published from this repository triggers a pipeline that regenerates all supported FHIR versions, runs a Rector cleanup pass (see Contributing → Code Quality), and pushes a matching commit + release to php-fhir-generated. You never need to run the generator yourself unless you want a custom namespace, a subset of versions, or non-default behavior.

Parse a resource with the pre-built package

After installing dcarbone/php-fhir-generated, Composer's autoloader makes the generated classes available. Pass the FHIR version when parsing so resource names resolve against the right model:

<?php declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use DCarbone\PHPFHIRGenerated\Encoding\ResourceParser;
use DCarbone\PHPFHIRGenerated\Versions\R4\Types\FHIRResource\FHIRDomainResource\FHIRPatient;
use DCarbone\PHPFHIRGenerated\Versions\R4\Version;

$version = new Version();
$json = '{"resourceType":"Patient","name":[{"family":"Example"}]}';
$patient = ResourceParser::parse($version, $json);

if (!$patient instanceof FHIRPatient) {
    throw new \UnexpectedValueException('Expected an R4 Patient resource.');
}

$errors = $patient->_getValidationErrors();
if ([] !== $errors) {
    throw new \DomainException('Patient did not pass generated validation.');
}

echo json_encode($patient, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR), PHP_EOL;

📖 Documentation

Full documentation is maintained on the project wiki:

Page Description
Getting Started Prerequisites, installation, and downloading FHIR schemas
CLI Usage Running the generator from the command line
Configuration Reference All Config and VersionConfig options
Architecture How the generator pipeline works internally
Profiles Generating classes for FHIR profiles such as US Core
Generated Code Understanding the output: namespaces, types, client, encoding
Cross-Version Translation Beta translation, code mapping, xver round trips, and custom translators
Testing Running tests on the generator and on generated code
Contributing Developer workflow and code-style notes

Support Matrix

PHPFHIR Version PHP Versions FHIR Versions Supported
v4 >= 8.1 DSTU1, DSTU2, STU3, R4, R4B, R5 Yes
v3 >= 8.1, < 8.5 DSTU1, DSTU2, STU3, R4, R4B, R5 No
v2 5.4–7.4 DSTU1, DSTU2, STU3, R4 No

R6 pre-release metadata is recognized, but R6 generation is not included in the default configuration or the generated-package release workflow yet.

Requirements

  • PHP 8.1 or newer
  • Composer — getcomposer.org
  • PHP extensions: ctype, curl, dom, json, libxml, simplexml, xmlreader, xmlwriter
  • FHIR schemas: extracted XSD bundles for each version you wish to generate (see the Getting Started wiki page for download links)

Quick Start

1. Install

# Standalone
git clone https://github.com/dcarbone/php-fhir.git
cd php-fhir && composer install

# — or as a Composer dependency in your own project —
composer require dcarbone/php-fhir

2. Download FHIR Schemas

mkdir -p fhir-schemas/R4
curl -Lo fhir-schemas/R4.zip https://hl7.org/fhir/R4/fhir-codegen-xsd.zip
unzip fhir-schemas/R4.zip -d fhir-schemas/R4

3. Generate

Option A — PHP script:

Create the output directories first. Omit testsPath below if you do not want generated tests.

mkdir -p output/src output/tests
<?php declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use DCarbone\PHPFHIR\Builder;
use DCarbone\PHPFHIR\Config;
use DCarbone\PHPFHIR\Config\VersionConfig;

$config = new Config(
    libraryPath: __DIR__ . '/output/src',
    versions: [
        new VersionConfig(name: 'R4', schemaPath: __DIR__ . '/fhir-schemas/R4'),
    ],
    testsPath: __DIR__ . '/output/tests',   // optional
);

$builder = new Builder($config);
$builder->render();

Option B — CLI (standalone checkout only):

./bin/generate.sh --versions R4 --logLevel info

See the CLI Usage and Configuration Reference wiki pages for full details.

4. Profiles (optional)

Classes for FHIR profiles such as US Core can be generated from local implementation guide packages. Pass a profilesConfig to the version, configuring every package the guide depends on as a package of its own and listing it under dependencies:

new VersionConfig(
    name: 'R4',
    schemaPath: __DIR__ . '/fhir-schemas/R4',
    profilesConfig: [
        'packages' => [
            ['name' => 'hl7.fhir.r4.core', 'source' => __DIR__ . '/input/hl7.fhir.r4.core.tgz'],
            // ... the guide's other dependencies ...
            [
                'name' => 'hl7.fhir.us.core',
                'source' => __DIR__ . '/input/hl7.fhir.us.core.tgz',
                'dependencies' => ['hl7.fhir.r4.core', /* ... */],
            ],
        ],
    ],
),

US Core needs eight packages besides its own; bin/config.php has the complete setup.

Each profile class extends the type it constrains, is nested under a Profiles namespace mirroring the Types layout, and is checked by the regular validation system (cardinality, fixed/pattern values, bindings, slices). Set the profileResolution unserialize option to auto to have parsing pick the profile class from meta.profile. Profile generation is memory hungry; allow PHP at least 1 GB. See the Profiles wiki page.

5. Cross-version translation (beta)

Generate R4 and R5 together, including the shared core, before running this example. Add R5's schema directory to versions alongside R4; see Getting Started for schema downloads. Use a generator revision containing the translation API; older pre-built packages may not include it.

<?php declare(strict_types=1);

use DCarbone\PHPFHIRGenerated\Autoloader;
use DCarbone\PHPFHIRGenerated\Translation\OnUnmappableFieldEnum;
use DCarbone\PHPFHIRGenerated\Translation\TranslationConfig;
use DCarbone\PHPFHIRGenerated\Translation\Translator;
use DCarbone\PHPFHIRGenerated\Versions\R4\Types\FHIRResource\FHIRDomainResource\FHIRPatient;
use DCarbone\PHPFHIRGenerated\Versions\R5\Version as R5Version;

require __DIR__ . '/output/src/DCarbone/PHPFHIRGenerated/Autoloader.php';
Autoloader::register();

$source = new FHIRPatient(active: true);
$translator = new Translator(new TranslationConfig(
    onUnmappableField: OnUnmappableFieldEnum::THROW,
));
$result = $translator->translate($source, new R5Version());

echo json_encode($result->getResource(), JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR), PHP_EOL;

Matching fields can be translated without a package. Optional local HL7 xver packages add directional Coding.system/Coding.code mappings and official extensions for supported missing fields. Maps that specify a source code-system version require an exact Coding.version match; declared target versions are applied. The default EXTENSION policy emits those extensions and restores compatible fields on the reverse hop; it throws when an unmappable value cannot be preserved. DROP instead discards unmappable values and records notices.

Beta: Translation is not lossless or a guarantee of semantic equivalence, and it does not automatically validate the target. Retain the source, inspect notices, and validate the result. The translation guide includes package configuration, a complete R5 Account → R4 → R5 example, code-mapping notices, and custom translators for rules such as bare Encounter.status codes.

Links

Source https://github.com/dcarbone/php-fhir
Pre-generated code https://github.com/dcarbone/php-fhir-generated
Wiki / Docs https://github.com/dcarbone/php-fhir/wiki
HL7 FHIR https://hl7.org/fhir/

License

Apache License 2.0