PHPackages                             lifetrenz/hl7 - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. lifetrenz/hl7

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

lifetrenz/hl7
=============

HL7 parser, generator and sender.

3.1.2(2y ago)0702↑30.4%MITPHPPHP ^8.0

Since Oct 18Pushed 2y agoCompare

[ Source](https://github.com/lifetrenz/HL7)[ Packagist](https://packagist.org/packages/lifetrenz/hl7)[ RSS](/packages/lifetrenz-hl7/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (4)Versions (2)Used By (0)

[![CI Status](https://github.com/lifetrenz/hl7/actions/workflows/main_ci.yml/badge.svg?branch=master)](https://github.com/lifetrenz/HL7/actions)[![Total Downloads](https://camo.githubusercontent.com/db158668f7148ae3a602c35a4ce71d23006371c0c0fbf672962bd8db6ccdf9d1/68747470733a2f2f706f7365722e707567782e6f72672f6c6966657472656e7a2f686c372f646f776e6c6f616473)](https://packagist.org/packages/lifetrenz/hl7)[![Latest Stable Version](https://camo.githubusercontent.com/18b209752c256354436e707b50f2ed1a99ffff855406f1c53d86275f56c86c67/68747470733a2f2f706f7365722e707567782e6f72672f6c6966657472656e7a2f686c372f762f737461626c65)](https://packagist.org/packages/lifetrenz/hl7)[![License](https://camo.githubusercontent.com/b6439b4970f02cb771d45e88e5558887c815767c29973f307ffea5e674f3494a/68747470733a2f2f706f7365722e707567782e6f72672f6c6966657472656e7a2f686c372f6c6963656e7365)](https://packagist.org/packages/lifetrenz/hl7)

**Important: Minimum supported PHP version has been updated to 8.0
Last supported versions:
-&gt; PHP 7.0 or 7.1 =&gt; [1.5.4](https://github.com/lifetrenz/HL7/tree/1.5.4)
-&gt; PHP 7.2 =&gt; [2.0.2](https://github.com/lifetrenz/HL7/tree/2.0.2)
-&gt; PHP 7.4 =&gt; [2.1.7](https://github.com/lifetrenz/HL7/tree/2.1.7)**

Introduction
------------

[](#introduction)

A PHP-based HL7 v2.x Parsing, Generation and Sending library, inspired from the famous Perl Net-HL7 package.

Installation
------------

[](#installation)

```
composer require lifetrenz/hl7
```

Usage
-----

[](#usage)

### Import library

[](#import-library)

```
// First, import classes from the library as needed...
use Lifetrenz\HL7; // HL7 factory class
use Lifetrenz\HL7\Message; // If Message is used
use Lifetrenz\HL7\Segment; // If Segment is used
use Lifetrenz\HL7\Segments\MSH; // If MSH is used
// ... and so on
```

### Parsing

[](#parsing)

```
// Create a Message object from a HL7 string
$message = HL7::from("MSH|^~\\&|1|")->createMessage(); // Returns Message object

// Or, using Message class...
$message = new Message("MSH|^~\\&|1|\rPID|||abcd|\r"); // Either \n or \r can be used as segment endings

// Get string form of the message
echo $message->toString(true);

// Extracting segments and fields from a Message object...
$message->getSegmentByIndex(1); // Get the first segment
$message->getSegmentsByName('ABC'); // Get an array of all 'ABC' segments
$message->getFirstSegmentInstance('ABC'); // Returns the first ABC segment. Same as $message->getSegmentsByName('ABC')[0];

// Check if a segment is present in the message object
$message->hasSegment('ABC'); // return true or false based on whether PID is present in the $message object

// Check if a message is empty
$message = new Message();
$message->isempty(); // Returns true
```

### Composing new messages

[](#composing-new-messages)

```
// The class `HL7` can be used to build HL7 object. It is a factory class with various helper methods to help build a hl7.
$message = HL7::build()->createMessage(); // Creates an empty message

// The HL7 factory class provides methods that can be chained together in a fluent fashion
$message = HL7::build()
    ->withComponentSeparator('#')
    ->withFieldSeparator('-')
    ->createMessage();

// Or, using Message class...
$message = new Message();
```

#### Message constructor parameters

[](#message-constructor-parameters)

```
// When a message is composed using Message class, there are multiple parameters available to define the properties of the HL7.
// Note: All of these properties are available as fluent methods in HL7 factory class (shown above). So it's recommended to use that for readability

// Creating multiple message objects may have an unexpected side effect: segments start with wrong index values (Check tests/MessageTest for explanation)...
// Use 4th argument as true, or call resetSegmentIndices() on $message object to reset segment indices to 1
$message = new Message("MSH|^~\&|||||||ORM^O01||P|2.3.1|", null, true, true);
// ... any segments added here will now start index from 1, as expected.
```

```
// Sometimes you may want to have exact index values, rather than auto-incrementing for each instance of a segment
// Use 5th argument as false...
$hl7String = "MSH|^~\&|||||||ORU^R01|00001|P|2.3.1|\n" . "OBX|1||11^AA|\n" . "OBX|1||22^BB|\n";
$message = new Message($hl7String, null, true, true, false); $// $message contains both OBXs with given indexes in the string
```

```
// Create a segment with empty sub-fields retained
$message = new Message("MSH|^~\\&|1|\rPV1|1|O|^AAAA1^^^BB|", null, true); // Third argument 'true' forces to keep all sub-fields
$pv1 = $message->getSegmentByIndex(1);
$fields = $pv1->getField(3); // $fields is ['', 'AAAA1', '', '', 'BB']

// Create/send message with segment-ending bar character (|) removed
$message = new Message("MSH|^~\\&|1|\nABC|||xxx\n", ['SEGMENT_ENDING_BAR' => false]);
$message->toString(true); // Returns "MSH|^~\&|1\nABC|||xxx\n"
(new Connection($ip, $port))->send($message); // Sends the message without ending bar-characters (details on Connection below)

// Specify custom values for separators, HL7 version etc.
$message = new Message("MSH|^~\\&|1|\rPV1|1|O|^AAAA1^^^BB|", ['SEGMENT_SEPARATOR' => '\r\n', 'HL7_VERSION' => '2.3']);

// Segment with separator character (~) creates sub-arrays containing each sub-segment
$message = new Message("MSH|^~\&|||||||ADT^A01||P|2.3.1|\nPID|||3^0~4^1"); // Creates [[3,0], [4,1]]

// To create a single array instead, pass 'true' as 6th argument. This may be used to retain behavior from previous releases
// Notice: Since this leads to a non-standard behavior, it may be removed in future
$message = new Message("MSH|^~\&|||||||ADT^A01||P|2.3.1|\nPID|||3^0~4^1", null, false, false, true, true); // Creates ['3', '0~4', '1']
// or
$message = new Message("MSH|^~\&|||||||ADT^A01||P|2.3.1|\nPID|||3^0~4^1", doNotSplitRepetition: true); // Creates ['3', '0~4', '1']
```

#### Handling segments and fields

[](#handling-segments-and-fields)

```
// Once a message object is created, we can now add, insert, set segments and fields.

// Create a MSH segment and add to message object
$msh = new MSH();
$message->addSegment($msh); // Message is: "MSH|^~\&|||||20171116140058|||2017111614005840157||2.3|\n"

// Create a custom segment
$abc = new Segment('ABC');
$abc->setField(1, 'xyz');
$abc->setField(2, 0);
$abc->setField(4, ['']); // Set an empty field at 4th position. 2nd and 3rd positions will be automatically set to empty
$abc->clearField(2); // Clear the value from field 2
$message->setSegment($abc, 1); // Message is now: "MSH|^~\&|||||20171116140058|||2017111614005840157||2.3|\nABC|xyz|\n"

// Create a defined segment (To know which segments are defined in this package, look into Segments/ directory)
// Advantages of defined segments over custom ones (shown above) are 1) Helpful setter methods, 2) Auto-incrementing segment index
$pid = new PID(); // Automatically creates PID segment, and adds segment index at PID.1
$pid->setPatientName([$lastname, $firstname, $middlename, $suffix]); // Use a setter method to add patient's name at standard position (PID.5)
$pid->setField('abcd', 5); // Apart from standard setter methods, you can manually set a value at any position too
unset($pid); // Destroy the segment and decrement the id number. Useful when you want to discard a segment.
```

### Send messages to remote listeners

[](#send-messages-to-remote-listeners)

Side note: In order to run Connection you need to install PHP ext-sockets

```
$ip = '127.0.0.1'; // An IP
$port = '12001'; // And Port where a HL7 listener is listening
$message = new Message($hl7String); // Create a Message object from your HL7 string

// Create a Socket and get ready to send message. Optionally add timeout in seconds as 3rd argument (default: 10 sec)
$connection = new Connection($ip, $port);
$response = $connection->send($message); // Send to the listener, and get a response back
echo $response->toString(true); // Prints ACK from the listener
```

### ACK

[](#ack)

Handle ACK message returned from a remote HL7 listener...

```
$ack = (new Connection($ip, $port))->send($message); // Send a HL7 to remote listener
$returnString = $ack->toString(true);
if (strpos($returnString, 'MSH') === false) {
    echo "Failed to send HL7 to 'IP' => $ip, 'Port' => $port";
}
$msa = $ack->getFirstSegmentInstance('MSA');
$ackCode = $msa->getAcknowledgementCode();
if ($ackCode[1] === 'A') {
    echo "Received ACK from remote\n";
}
else {
    echo "Received NACK from remote\n";
    echo "Error text: " . $msa->getTextMessage();
}
```

Create an ACK response from a given HL7 message:

```
$msg = new Message("MSH|^~\\&|1|\rABC|1||^AAAA1^^^BB|", null, true);
$ackResponse = new ACK($msg);
```

Options can be passed while creating ACK object:

```
$msg = new Message("MSH|^~\\&|1|\rABC|1||^AAAA1^^^BB|", null, true);
$ackResponse = new ACK($msg, null, ['SEGMENT_SEPARATOR' => '\r\n', 'HL7_VERSION' => '2.5']);
```

APIs
----

[](#apis)

This package exposes a number of public methods for convenient HL7 handling. Some examples are:

1. Considering you have a Message object (say, `$msg = new Message(file_get_contents('somefile.hl7'));`)

```
    $msg->toFile('/path/to/some.hl7'); // Write to a file
    $msg->isOru(); // Check if it's an ORU
    $msg->isOrm(); // Check if it's an ORM
```

Visit [docs\\README](docs/README.md) for details on available APIs

All segment level getter/setter APIs can be used in two ways -

- If a position index isn't provided as argument (1st argument for getters, 2nd for setters), a standard index is used.
    `$pid->setPatientName('John Doe')` -&gt; Set patient name at position 5 as per HL7 v2.3 [standard](https://corepointhealth.com/resource-center/hl7-resources/hl7-pid-segment)
    `$pid->getPatientAddress()` -&gt; Get patient address from standard 11th position
- To use a custom position index, provide it in the argument:
    `$pid->setPatientName('John Doe', 6)` -&gt; Set patient name at 6th position in PID segment
    `$pid->getPatientAddress(12)` -&gt; Get patient address from 12th position

### Issues

[](#issues)

Bug reports and feature requests can be submitted on the [Github Issue Tracker](https://github.com/lifetrenz/HL7/issues).

### Contributing

[](#contributing)

See [CONTRIBUTING.md](CONTRIBUTING.md) for information.

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity16

Limited adoption so far

Community17

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 72.5% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

934d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/21240c1429f3f4d5a22e4417b17a2c3438d0af7a6b5189a83bbc76a50695463d?d=identicon)[lifetrenz](/maintainers/lifetrenz)

---

Top Contributors

[![senaranya](https://avatars.githubusercontent.com/u/5471894?v=4)](https://github.com/senaranya "senaranya (58 commits)")[![JerryMSunny](https://avatars.githubusercontent.com/u/4510274?v=4)](https://github.com/JerryMSunny "JerryMSunny (3 commits)")[![isangil](https://avatars.githubusercontent.com/u/403087?v=4)](https://github.com/isangil "isangil (2 commits)")[![ajibarra](https://avatars.githubusercontent.com/u/794722?v=4)](https://github.com/ajibarra "ajibarra (2 commits)")[![DurandSacha](https://avatars.githubusercontent.com/u/29280692?v=4)](https://github.com/DurandSacha "DurandSacha (1 commits)")[![fernando-rivas-smtp](https://avatars.githubusercontent.com/u/85176850?v=4)](https://github.com/fernando-rivas-smtp "fernando-rivas-smtp (1 commits)")[![henry11996](https://avatars.githubusercontent.com/u/51729131?v=4)](https://github.com/henry11996 "henry11996 (1 commits)")[![lampi87](https://avatars.githubusercontent.com/u/3034138?v=4)](https://github.com/lampi87 "lampi87 (1 commits)")[![maxence-machu](https://avatars.githubusercontent.com/u/23130568?v=4)](https://github.com/maxence-machu "maxence-machu (1 commits)")[![mmonahanfl](https://avatars.githubusercontent.com/u/36053511?v=4)](https://github.com/mmonahanfl "mmonahanfl (1 commits)")[![peter279k](https://avatars.githubusercontent.com/u/9021747?v=4)](https://github.com/peter279k "peter279k (1 commits)")[![pluk77](https://avatars.githubusercontent.com/u/524179?v=4)](https://github.com/pluk77 "pluk77 (1 commits)")[![samuel-chane](https://avatars.githubusercontent.com/u/47699407?v=4)](https://github.com/samuel-chane "samuel-chane (1 commits)")[![silvioq](https://avatars.githubusercontent.com/u/155036?v=4)](https://github.com/silvioq "silvioq (1 commits)")[![svenvanhees](https://avatars.githubusercontent.com/u/3237025?v=4)](https://github.com/svenvanhees "svenvanhees (1 commits)")[![tysonlist](https://avatars.githubusercontent.com/u/3150363?v=4)](https://github.com/tysonlist "tysonlist (1 commits)")[![arnowelzel](https://avatars.githubusercontent.com/u/6613614?v=4)](https://github.com/arnowelzel "arnowelzel (1 commits)")[![DamienHarper](https://avatars.githubusercontent.com/u/2448660?v=4)](https://github.com/DamienHarper "DamienHarper (1 commits)")[![dmelskyi](https://avatars.githubusercontent.com/u/15121564?v=4)](https://github.com/dmelskyi "dmelskyi (1 commits)")

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/lifetrenz-hl7/health.svg)

```
[![Health](https://phpackages.com/badges/lifetrenz-hl7/health.svg)](https://phpackages.com/packages/lifetrenz-hl7)
```

###  Alternatives

[mtdowling/jmespath.php

Declaratively specify how to extract elements from a JSON document

2.0k472.8M135](/packages/mtdowling-jmespathphp)[opis/closure

A library that can be used to serialize closures (anonymous functions) and arbitrary data.

2.6k230.0M283](/packages/opis-closure)[masterminds/html5

An HTML5 parser and serializer.

1.8k242.8M226](/packages/masterminds-html5)[sabberworm/php-css-parser

Parser for CSS Files written in PHP

1.8k191.2M63](/packages/sabberworm-php-css-parser)[michelf/php-markdown

PHP Markdown

3.5k52.4M343](/packages/michelf-php-markdown)[jms/metadata

Class/method/property metadata management in PHP

1.8k152.8M88](/packages/jms-metadata)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
