PHPackages                             aranyasen/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. aranyasen/hl7

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

aranyasen/hl7
=============

HL7 parser, generator and sender.

4.0.0(2mo ago)1951.3M—9.3%87[13 issues](https://github.com/senaranya/HL7/issues)[9 PRs](https://github.com/senaranya/HL7/pulls)MITPHPPHP &gt;=8.2CI passing

Since Nov 16Pushed 1mo ago12 watchersCompare

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

READMEChangelog (10)Dependencies (5)Versions (69)Used By (0)

[![CI Status](https://github.com/senaranya/hl7/actions/workflows/main_ci.yml/badge.svg?branch=master)](https://github.com/senaranya/HL7/actions)[![Total Downloads](https://camo.githubusercontent.com/0f30d9a56290153508243c37c550bb240c1f222b719cf5e743c01d4555dee37c/68747470733a2f2f706f7365722e707567782e6f72672f6172616e796173656e2f686c372f646f776e6c6f616473)](https://packagist.org/packages/aranyasen/hl7)[![Latest Stable Version](https://camo.githubusercontent.com/c9b8d80112dc9b469a64eec491d6595c2c50e664b93f165d1eea99c3027aabe2/68747470733a2f2f706f7365722e707567782e6f72672f6172616e796173656e2f686c372f762f737461626c65)](https://packagist.org/packages/aranyasen/hl7)[![License](https://camo.githubusercontent.com/503727685e2e123d8e9efddd52e45dc150fb45c347ac7f737f4e712c5a340d2f/68747470733a2f2f706f7365722e707567782e6f72672f6172616e796173656e2f686c372f6c6963656e7365)](https://packagist.org/packages/aranyasen/hl7)

Release announcement:
---------------------

[](#release-announcement)

### Version 4.0 (Breaking Release)

[](#version-40-breaking-release)

⚠️ **This release contains breaking changes.**If you are upgrading from **3.x**, please read the [Guide](UPGRADE.md) before upgrading.

#### Key Changes

[](#key-changes)

- Minimum supported PHP version is now **8.2**
- `Message` must start with a `MSH` segment
- `InvalidArgumentException` replaced with `HL7Exception`
- `new Message()` is now **deprecated** (use `HL7` factory instead)
- `setSegment()` is deprecated (use `insertSegment()` instead)
- In `insertSegment()` method, only MSH can be inserted now in the 0th index
- `withSegmentSeparator()` in HL7 factory accepts CRLF (`\r\n`) as argument. Any other multi-character separator will continue to throw exception

If something breaks after upgrading:

- Report bugs or request features at [Issues](https://github.com/senaranya/HL7/issues)
- Submit fixes at [Pull Requests](https://github.com/senaranya/HL7/pulls)

---

Important
---------

[](#important)

- The global setting `SEGMENT_ENDING_BAR` is deprecated and will be removed in a future release. If you're using this in your code, replace it with `WITH_SEGMENT_ENDING_FIELD_SEPARATOR`

PHP Compatibility
-----------------

[](#php-compatibility)

PHP VersionPackage Version8.2+4.x8.0 – 8.1[3.2.2](https://github.com/senaranya/HL7/tree/3.2.2)7.4[2.1.7](https://github.com/senaranya/HL7/tree/2.1.7)7.2[2.0.2](https://github.com/senaranya/HL7/tree/2.0.2)7.0 – 7.1[1.5.4](https://github.com/senaranya/HL7/tree/1.5.4)Introduction
------------

[](#introduction)

This is a PHP package to create, parse and send HL7 v2 messages. This was originally inspired from Net-HL7 Perl package.

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

[](#installation)

```
composer require aranyasen/hl7
```

Usage
-----

[](#usage)

### Parsing

[](#parsing)

```
// Create a Message object from a HL7 string
use Aranyasen\HL7;
$message = HL7::from("MSH|^~\\&|1|")->create();
$message = HL7::from("MSH|^~\\&|1|\rPID|||abcd|\r")->create(); // Creates Message object with two segments with \r as segment ending (\n can also be used)

// 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 = HL7::build()->create();
$message->removeSegmentsByName('MSH')
$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()->create(); // Creates a Message containing MSH segment with default separators, version etc.
```

#### Configuring HL7 messages

[](#configuring-hl7-messages)

```
// The HL7 factory class provides methods that can be chained together in a fluent fashion. These can be used to
// override the defaults
$message = HL7::build()
    ->withComponentSeparator('#') // Use # as the component separator instead of the default ^
    ->withFieldSeparator('-') // Use - as the field separator instead of the default |
    ->withSegmentSeparator('\r\n') // Override segment separator
    ->withHL7Version('2.3') // Use HL7 version 2.3
    ->create();
```

```
// Creating multiple message objects may have an unexpected side effect: segments start with wrong index values (Check tests/MessageTest for explanation)...
// So to reset segment indices to 1:
HL7::from("MSH|^~\&|||||||ORM^O01||P|2.3.1|")->resetIndices()->create(); // Use resetIndices() while creating a new message
$message->resetSegmentIndices(); // or call resetSegmentIndices() on an existing $message object
// ... 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
$hl7String = "MSH|^~\&|||||||ORU^R01|00001|P|2.3.1|\n" . "OBX|1||11^AA|\n" . "OBX|1||22^BB|\n";
$message = HL7::from($hl7String)
    ->autoIncrementIndices(false)
    ->create();
// $message now contains both OBXs with 1 as the index, instead of 1 and 2
```

```
// Ensure empty sub-fields are not removed
// Note: We should perhaps _always_ use this while creating a message object, as we don't want empty subfields removed. In future versions, this will be the default
$message = HL7::from("MSH|^~\\&|1|\rPV1|1|O|^AAAA1^^^BB|")->keepEmptySubfields()->create();
$pv1 = $message->getSegmentByIndex(1);
$fields = $pv1->getField(3); // $fields is ['', 'AAAA1', '', '', 'BB']

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

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

// To create a single array instead, use doNotSplitRepetition()
// Note: Since this leads to a non-standard behavior, it may be removed in future
$message = HL7::from("MSH|^~\&|||||||ADT^A01||P|2.3.1|\nPID|||3^0~4^1")
    ->doNotSplitRepetition()
    ->create(); // 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
use Aranyasen\HL7\Segments\MSH;
$msh = new MSH();
$message->addSegment($msh); // Message is: "MSH|^~\&|||||20171116140058|||2017111614005840157||2.3|\n"

// Create a custom segment
use Aranyasen\HL7\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->insertSegment($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
use Aranyasen\HL7\Segments\PID;
$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.

// It is possible that segments get added in a way that the Set IDs/Sequence IDs within the message are not in order or leave gaps. To reset all Set/Sequence IDs in the message:

$message->reindexSegments();
```

### 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 = HL7::from($hl7String)->create(); // Create a Message object from your HL7 string. See above for details

// 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...

```
use Aranyasen\HL7\Connection;
$ack = (new Connection($ip, $port))->send($message); // Send a HL7 to remote listener
$returnString = $ack->toString(true);
if (str_contains($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:

```
use Aranyasen\HL7\Messages\ACK;
$msg = HL7::from("MSH|^~\\&|1|\rABC|1||^AAAA1^^^BB|")->keepEmptySubfields()->create();
$ackResponse = new ACK($msg);
```

Options can be passed while creating ACK object:

```
$msg = HL7::from("MSH|^~\\&|1|\rABC|1||^AAAA1^^^BB|")->keepEmptySubfields()->create();
$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/senaranya/HL7/issues).

### Contributing

[](#contributing)

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

###  Health Score

71

—

ExcellentBetter than 100% of packages

Maintenance87

Actively maintained with recent releases

Popularity60

Solid adoption and visibility

Community30

Small or concentrated contributor base

Maturity90

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 67.8% 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

Every ~47 days

Recently: every ~100 days

Total

65

Last Release

63d ago

Major Versions

1.10.1 → 2.0.02020-09-12

2.1.7 → 3.0.02022-12-31

3.2.2 → 4.x-dev2026-03-16

PHP version history (5 changes)1.0.0PHP &gt;=7.1

1.6.0PHP &gt;=7.2

2.0.3PHP &gt;=7.3

3.0.0PHP ^8.0

4.x-devPHP &gt;=8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/16dd57009f577d06da0eb45b9020ed46e7da99b2e26eda5dde49da9f74e66612?d=identicon)[senaranya](/maintainers/senaranya)

---

Top Contributors

[![senaranya](https://avatars.githubusercontent.com/u/5471894?v=4)](https://github.com/senaranya "senaranya (61 commits)")[![jay-knight](https://avatars.githubusercontent.com/u/42975397?v=4)](https://github.com/jay-knight "jay-knight (3 commits)")[![isangil](https://avatars.githubusercontent.com/u/403087?v=4)](https://github.com/isangil "isangil (2 commits)")[![skeemer](https://avatars.githubusercontent.com/u/864069?v=4)](https://github.com/skeemer "skeemer (2 commits)")[![luilliarcec](https://avatars.githubusercontent.com/u/27895611?v=4)](https://github.com/luilliarcec "luilliarcec (2 commits)")[![ajibarra](https://avatars.githubusercontent.com/u/794722?v=4)](https://github.com/ajibarra "ajibarra (2 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)")[![Oleg-Vartanov](https://avatars.githubusercontent.com/u/61663204?v=4)](https://github.com/Oleg-Vartanov "Oleg-Vartanov (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)")[![rodrigoprimo](https://avatars.githubusercontent.com/u/77215?v=4)](https://github.com/rodrigoprimo "rodrigoprimo (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)")[![Xusifob](https://avatars.githubusercontent.com/u/8103268?v=4)](https://github.com/Xusifob "Xusifob (1 commits)")[![arnowelzel](https://avatars.githubusercontent.com/u/6613614?v=4)](https://github.com/arnowelzel "arnowelzel (1 commits)")

---

Tags

hl7hl7-builderhl7-messagehl7-parserhl7-sendinghl7v2php-libraryphp7sendparsegeneratehl7

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

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

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

###  Alternatives

[olamedia/nokogiri

HTML Parser

23176.3k3](/packages/olamedia-nokogiri)[nihongodera/limelight

A php Japanese language text analyzer and parser.

10678.9k](/packages/nihongodera-limelight)[adci/full-name-parser

Parses a human name

29714.4k5](/packages/adci-full-name-parser)[dimabdc/php-fast-simple-html-dom-parser

PHP Fast Simple HTML DOM parser.

9352.6k](/packages/dimabdc-php-fast-simple-html-dom-parser)[jstewmc/rtf

Read and write Rich Text Format (RTF) documents with PHP

44127.5k6](/packages/jstewmc-rtf)[shaarli/netscape-bookmark-parser

Generic Netscape bookmark parser

2643.1k](/packages/shaarli-netscape-bookmark-parser)

PHPackages © 2026

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