Download the PHP package pietercolpaert/hardf without Composer
On this page you can find all versions of the php package pietercolpaert/hardf. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download pietercolpaert/hardf
More information about pietercolpaert/hardf
Files in pietercolpaert/hardf
Package hardf
Short Description A fast parser for RDF serializations such as turtle, n-triples, n-quads, trig and N3
License MIT
Homepage https://github.com/pietercolpaert/hardf
Informations about the package hardf
The Hardf RDF 1.2 Turtle, N-Triples, N-Quads, and TriG parser for PHP
Hardf is a PHP 7.1+ library that lets you handle Linked Data (RDF 1.2). It offers N-Quads. Both the parser and the serializer have streaming support.
Hardf also supports RDF 1.2 features that are relevant to this representation, including triple terms, reified triples, annotation syntax, directional language literals, VERSION declarations, and RDF Messages. Conformances is tested using the official test suites.
This library was started as a port of N3.js to PHP.
Triple Representation
On purpose, we focused on performance, and not on developer friendliness. We have thus implemented this triple representation using associative arrays rather than PHP objects. For example:
Encode literals as follows (similar to N3.js):
RDF 1.2 triple terms are represented as structured arrays, not as serialized strings:
Parser callbacks and parse() return values can therefore contain either strings or triple-term arrays in the object position. TriGWriter accepts triple-term arrays in subject and object positions.
Library functions
Install this library using composer:
Writing
A class that can be instantiated to write TriG or Turtle.
Example use:
All methods
RDF Messages
To write an RDF Message Log, create the writer with messages => true and call addMessage() for each message. If you also pass a version, Hardf will emit a VERSION declaration with the -messages suffix automatically.
This writes:
Parsing
Next to TriG, the TriGParser class also parses Turtle, N-Triples, and N-Quads.
RDF 1.2 triple terms are emitted as arrays with type => TripleTerm. Reified triple syntax emits an rdf:reifies triple whose object is such a triple term.
RDF Message Logs are enabled by a VERSION label with the -messages suffix, such as VERSION "1.2-messages". When parsing in streaming mode, the triple callback receives the current message counter as its fourth argument. Blank node labels are scoped per message, so the same blank node labels may legally reappear in later messages.
If you construct the parser with messages => true and use parse() without a callback, Hardf returns the parsed data as an array of messages, where each message is an array of quads.
All methods
The triple callback signature is:
For normal RDF parsing, $messageCounter stays null. In RDF Message mode, it starts at 0 for the first message and increments at each MESSAGE or @message delimiter.
When messages => true is set and no callback is passed, the return type becomes effectively:
That is, an array of messages, each containing an array of quads.
Basic examples for small files
Using return values and passing these to a writer:
Using callbacks and passing these to a writer:
Parsing RDF 1.2 triple terms:
Example using chunks and keeping prefixes
When you need to parse a large file, you will want to parse chunks and process them incrementally. You can do that as follows:
Parsing RDF Messages
The callback is invoked in two distinct situations:
- Triple event —
$tripleis set,$prefixesisnull.$messageCounteris the index (starting at0) of the message this triple belongs to. - End-of-stream event —
$tripleisnulland$prefixesis an array (possibly empty).$messageCounteris the index of the last active message (the one that was still open when the stream ended).
If you want the whole RDF Message Log at once instead of streaming callbacks:
Parser options
formatinput format (case-insensitive)blankNodePrefix(defaults tob0_) prefix forced on blank node names, e.g.TriGParser(["blankNodePrefix" => 'foo'])will parse_:baras_:foobar.documentIRIsets the base URI used to resolve relative URIs (not applicable ifformatindicates n-triples or n-quads)lexerallows usage of your own lexer class. A lexer must provide the following public methods:tokenize(string $input, bool $finalize = true): array<array{'subject': string, 'predicate': string, 'object': string, 'graph': string}>tokenizeChunk(string $input): array<array{'subject': string, 'predicate': string, 'object': string, 'graph': string}>end(): array<array{'subject': string, 'predicate': string, 'object': string, 'graph': string}>
explicitQuantifiers- [...]
Empty document base IRI
Some Turtle and N3 documents may use relative-to-the-base-IRI IRI syntax (see here and here), e.g.
To properly parse such documents the document base IRI must be known. Otherwise we might end up with empty IRIs (e.g. for the subject in the example above).
Sometimes the base IRI is encoded in the document, e.g.
but sometimes it is missing.
In such a case, the Turtle specification requires us to follow section 5.1.1 of RFC 3986, which says that if the base IRI is not specified in the document, it should be assumed to be the document retrieval URI (e.g. the URL you downloaded the document from or a file path converted to a URL). Unfortunately, this cannot be guessed by the Hardf parser and has to be provided using the documentIRI parser option, e.g.
Long story short: if you run into the subject/predicate/object on line X can not be parsed without knowing the the document base IRI.(...) error, please initialize the parser with the documentIRI option.
Utility
A static class with a couple of helpful functions for handling our specific triple representation. It helps you create and evaluate literals and IRIs, and expand prefixes.
See the documentation at https://github.com/RubenVerborgh/N3.js#utility for more information.
Two executables
We also offer 2 simple tools in bin/ as an example implementation: one validator and one translator. Try for example:
RDF Working Group Test Suites
The official RDF Working Group test manifests live in w3c/rdf-tests. RDF 1.2 manifests are available under rdf/rdf12, including Turtle, TriG, N-Triples, and N-Quads suites.
This repository includes an optional rdf-test-suite.js bridge in spec/. The JavaScript runner loads the W3C manifests, and spec/hardf-rdf-test-engine.js delegates parsing to spec/hardf-rdf-test-parser.php.
Install the optional Node dependencies:
Run individual RDF 1.2 leaf manifests:
Or run grouped compliance reports that also include the relevant RDF 1.1 parser manifests:
Generate machine-readable EARL output by using the scripts with the :earl suffix. The metadata is defined in spec/earl-metadata.json.
All RDF 1.2 compliance commands pass. The RDF 1.2 root manifests also include C14N tests, but rdf-test-suite.js does not currently provide handlers for the RDF 1.2 C14N test types.
RDF/XML and RDF semantics manifests are not wired because hardf does not implement RDF/XML parsing or entailment. The compliance scripts in this repository therefore focus on the RDF parser manifests for Turtle, TriG, N-Triples, and N-Quads.
Performance
In the PHP ecosystem, Hardf is the only library here that supports RDF 1.1 and RDF 1.2 features such as named graphs and triple terms. EasyRDF and ARC2 are still useful comparison points, but they do not cover that full feature set.
Because of that, the benchmark below uses a generated N-Triples dataset, not TriG. The input is generated through Hardf's own TriGWriter in N-Triples mode and contains only plain triples, with a mix of IRI objects, literal objects, and occasional blank nodes. This gives all compared parsers the same RDF 1.0-compatible input while still reflecting realistic parser work.
The measurements below were taken with PHP 8.3.6 and Node.js 25.9.0 using php perf/compare-hardf-n3js.php. EasyRDF and ARC2 were measured with CLI opcache enabled. Hardf was measured both with and without CLI opcache enabled. N3.js is included as a reference implementation on a very fast runtime, so it is expected to win on absolute throughput.
The script generates synthetic N-Triples datasets at /tmp/hardf-perf/ and reports parse time and memory for each framework.
That expectation does show up in the results, but the interesting part is the size of the gap: Hardf remains within a single-digit factor of N3.js across the whole range and scales roughly linearly from $10^5$ to $10^7$ triples. CLI opcache helps Hardf modestly on runtime and significantly on reported PHP memory. EasyRDF and ARC2 fall further behind as the data grows.
We report on the findings for increasing number of triples.
Note that the memory figures are runtime-specific and therefore not perfectly comparable across languages: PHP reports memory_get_usage(), while Node.js reports V8 heapUsed. The timing results are the more meaningful cross-runtime comparison.
For 100,000 triples:
| framework | time (ms) | memory (MB) | slower than N3.js |
|---|---|---|---|
| Hardf without opcache | 382 | 1.849 | 3.41x |
| Hardf with opcache | 372 | 0.540 | 3.32x |
| EasyRDF with opcache | 303 | 181.346 | 2.71x |
| ARC2 with opcache | 1,133 | 83.435 | 10.12x |
| N3.js | 112 | 6.328 | 1.00x |
For 1,000,000 triples:
| framework | time (ms) | memory (MB) | slower than N3.js |
|---|---|---|---|
| Hardf without opcache | 3,961 | 1.849 | 4.62x |
| Hardf with opcache | 3,880 | 0.540 | 4.52x |
| EasyRDF with opcache | 4,247 | 1,788.624 | 4.95x |
| ARC2 with opcache | 12,463 | 826.056 | 14.53x |
| N3.js | 858 | 9.263 | 1.00x |
For 10,000,000 triples:
| framework | time (ms) | memory (MB) | slower than N3.js |
|---|---|---|---|
| Hardf without opcache | 41,607 | 1.849 | 5.19x |
| Hardf with opcache | 39,098 | 0.540 | 4.88x |
| EasyRDF with opcache | 125,834 | 18,041.405 | 15.70x |
| ARC2 with opcache | 147,273 | 8,352.265 | 18.37x |
| N3.js | 8,017 | 30.336 | 1.00x |
- N3.js on Node.js 25 is faster, which is expected, but Hardf stays surprisingly close for a native PHP parser: about
3.32xto4.88xslower with opcache enabled, and about3.41xto5.19xslower without it. - Hardf remains effective over the tested range and is substantially faster than ARC2 at every size, while also overtaking EasyRDF on the larger datasets.
License, status and contributions
The Hardf library is copyrighted by Ghent University - IMEC and contributors, and released under the MIT License.
Contributions are welcome, and bug reports or pull requests are always helpful. If you plan to implement a larger feature, it's best to discuss this first by filing an issue.