PHPackages                             peterdkc/parser - 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. [API Development](/categories/api)
4. /
5. peterdkc/parser

ActiveLibrary[API Development](/categories/api)

peterdkc/parser
===============

Simple PHP Parser Utility Library for API Development

v4.4.2(8y ago)22.5kMITPHPPHP &gt;=5.3.0

Since May 29Pushed 6y ago1 watchersCompare

[ Source](https://github.com/PeterDKC/Parser)[ Packagist](https://packagist.org/packages/peterdkc/parser)[ Docs](https://github.com/PeterDKC/Parser)[ RSS](/packages/peterdkc-parser/feed)WikiDiscussions master Synced 1w ago

READMEChangelog (1)Dependencies (5)Versions (32)Used By (0)

**Note:** This package is a fork and may / may not be maintained independently depending on whether the original maintainer starts maintaining his source as of 4/18/2018. Please use with caution and Watch the source repo for updates.

All the documentation below should still be relevant although items such as build status may not reflect reality for this fork.

Parser
======

[](#parser)

[![Latest Version on Packagist](https://camo.githubusercontent.com/4202bf28ad87fbebf9c5dfdbc605b99e77da14c8a73b3de807529b0aa8fcc8eb/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7065746572646b632f5061727365722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/peterdkc/parser)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![Build Status](https://camo.githubusercontent.com/fafc3560138737584025d06e80160d3e7746e1128a3abcb8816c67c42897631e/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f6e617468616e6d61632f5061727365722f6d61737465722e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/nathanmac/Parser)[![Coverage Status](https://camo.githubusercontent.com/cc84edd434b610f49d6c713607b8160bf5ad585b1b84fbd6da18e0a91cc4643d/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f636f7665726167652f672f6e617468616e6d61632f5061727365722e7376673f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/nathanmac/Parser/code-structure)[![Quality Score](https://camo.githubusercontent.com/e80f76d804fe43780f6f7d2fd57983d9f3dc745704a34239f6de447428f108de/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f6e617468616e6d61632f5061727365722e7376673f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/nathanmac/Parser)[![Total Downloads](https://camo.githubusercontent.com/ca4719ffd94105edb0465a2ece9bc001144a77aa8c1eb05c446842edcd22affb/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6e617468616e6d61632f5061727365722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/nathanmac/Parser)[![SensioLabsInsight](https://camo.githubusercontent.com/2f4e52a3ae8b3a6e64b9686590f49c09b881f7b784997302fa08dcbc45a3a857/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f63356263346133642d623935342d343930312d393035662d6364343966623863333938362f6d696e692e706e67)](https://insight.sensiolabs.com/projects/c5bc4a3d-b954-4901-905f-cd49fb8c3986)

Simple PHP Parser Library for API Development, parse a post http payload into a php array.

Also see the [Responder](https://github.com/nathanmac/Responder) library for handling output.

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

[](#installation)

Begin by installing this package through Composer. From the Terminal:

```
composer require peterdkc/parser

```

### Laravel/Lumen Users

[](#laravellumen-users)

Laravel/Lumen VerisonSupported Library VerisonLaravel/Lumen 5+&gt; 3.\*Laravel 42.\*#### Laravel Users (Adding the Service Provider)

[](#laravel-users-adding-the-service-provider)

If you are a Laravel user, then there is a service provider that you can make use of to automatically prepare the bindings and such.

Include the service provider within `app/config/app.php`.

```
'providers' => [
    '...',
    'Nathanmac\Utilities\Parser\ParserServiceProvider'
];
```

And, for convenience, add a facade alias to this same file at the bottom:

```
'aliases' => [
    '...',
    'Parser' => 'Nathanmac\Utilities\Parser\Facades\Parser',
];
```

#### Lumen Users (Adding the Service Provider)

[](#lumen-users-adding-the-service-provider)

If you are a Lumen user, then there is a service provider that you can make use of to automatically prepare the binding and such.

```
// bootstrap/app.php

$app->register('Nathanmac\Utilities\Parser\ParserServiceProvider');
```

Lumen users can also add the facade alias.

```
// bootstrap/app.php

class_alias('Nathanmac\Utilities\Parser\Facades\Parser', 'Parser');
```

#### Using the Facade

[](#using-the-facade)

```
public function index()
{
    Parser::payload('application/json');

    Parser::json($payload);		    // JSON > Array
    Parser::xml($payload);		    // XML > Array
    Parser::yaml($payload);		    // YAML > Array
    Parser::querystr($payload);	    // Query String > Array
    Parser::serialize($payload);	// Serialized Object > Array
	Parser::bson($payload);	        // BSON > Array
	Parser::msgpack($payload);	    // MSGPack > Array

    Parser::all();                         // Return all values
    Parser::has('key');                    // Does a key exist, with value.
    Parser::get('key', 'default value');   // Get value by key, set an optional default.
    Parser::only('id', 'name', 'email');   // Only return value from the selected keys.
    Parser::except('password');            // Don't return values from the selected keys.
    Parser::mask($mask);                   // Return masked values (see Mask Function, below).
}
```

All the examples below assume you *aren't* using Laravel (or Lumen), and therefore don't have access to the facade. As with any other facade, instead of:

```
$parser = new Parser();

$parser->{$method}($payload);
```

just use:

```
Parser::{$method}($payload);
```

Usage
-----

[](#usage)

### Parsing Functions

[](#parsing-functions)

```
$parser->json($payload);		// JSON > Array
$parser->xml($payload);		    // XML > Array
$parser->yaml($payload);		// YAML > Array
$parser->querystr($payload);	// Query String > Array
$parser->serialize($payload);	// Serialized Object > Array
$parser->bson($payload);     	// BSON > Array
$parser->msgpack($payload);   	// MSGPack > Array
```

#### Parse Input/Payload (PUT/POST)

[](#parse-inputpayload-putpost)

```
$parser = new Parser();
$parser->payload();		                // Auto Detect Type - 'Content Type' HTTP Header
$parser->payload('application/json');	// Specifiy the content type
```

#### Helper functions

[](#helper-functions)

```
$parser = new Parser();
$parser->all();                         // Return all values
$parser->has('key');                    // Does a key exist, with value.
$parser->get('key', 'default value');   // Get value by key, set an optional default.
$parser->only('id', 'name', 'email');   // Only return value from the selected keys.
$parser->except('password');            // Don't return values from the selected keys.
$parser->mask($mask);                   // Return masked values (see Mask Function, below).
```

#### Mask function

[](#mask-function)

The mask function processes payload data using a configuration mask, thereby returning only a selected subset of the data. It works just like the `only` method but with the added benefit of allowing you to specify a mask in the form of an array, this means you can generate masks on-the-fly based on system and/or user defined conditions.

##### Demo

[](#demo)

###### Mask

[](#mask)

Defining the mask, masks consist of basic array structure, for this particular example we have some rules for the data to be returned they include: - the title of the post - all the body's for all the comments.

```
$mask = [
    'post' => [
        'title' => '*',
        'comments' => [
            'body' => '*'
        ]
    ]
];
```

###### Sample Payload

[](#sample-payload)

```
{
    "post": {
        "title": "Hello World",
        "author": "John Smith",
        "comments": [
            {"body": "This is a comment", "date": "2015-02-20"},
            {"body": "This is another comment", "date": "2015-05-09"}
        ]
    }
}
```

###### Applying the Mask

[](#applying-the-mask)

```
    $parser = new Parser();
    $output = $parser->mask($mask);
```

###### Output

[](#output)

This is the output generated as a result of applying the mask against the sample payload provided above.

```
$output = [
    'post' => [
        'title' => 'Hello World',
        'comments' => [
            ['body' => 'This is a comment'],
            ['body' => 'This is another comment']
        ]
    ]
];
```

#### Wildcards/Special Keys (\*, %, :first, :last, :index\[0\], :item\[0\])

[](#wildcardsspecial-keys---first-last-index0-item0)

```
$parser = new Parser();
$parser->has('message.*');          // Does a key exist, with value. (Wildcard key returns first item found)
$parser->get('message.*');          // Get value by key. (Wildcard key returns first item found)
$parser->has('message.:first');     // Does a key exist, with value. (:first key returns first item found)
$parser->get('message.:first');     // Get value by key. (:first key returns first item found)
$parser->has('message.:last');      // Does a key exist, with value. (:last key returns last item found)
$parser->get('message.:last');      // Get value by key. (:last key returns last item found)
$parser->has('message.:index[0]');  // Does a key exist, with value. (:index[0] key returns item at index 0)
$parser->get('message.:index[0]');  // Get value by key. (:index[0] key returns item at index 0)
$parser->has('message.:item[0]');   // Does a key exist, with value. (:item[0] key returns item at index 0)
$parser->get('message.:item[0]');   // Get value by key. (:item[0] key returns item at index 0)
```

#### Parse JSON

[](#parse-json)

```
$parser = new Parser();
$parsed = $parser->json('
	{
		"message": {
			"to": "Jack Smith",
			"from": "Jane Doe",
			"subject": "Hello World",
			"body": "Hello, whats going on..."
		}
	}');
```

#### Parse XML

[](#parse-xml)

```
$parser = new Parser();
$parsed = $parser->xml('

					Created 5 minutes ago
					Jack Smith
					Jane Doe
					Hello World
					Hello, whats going on...

			');
```

#### Parse Query String

[](#parse-query-string)

```
$parser = new Parser();
$parsed = $parser->querystr('to=Jack Smith&from=Jane Doe&subject=Hello World&body=Hello, whats going on...');
```

#### Parse Serialized Object

[](#parse-serialized-object)

```
$parser = new Parser();
$parsed = $parser->serialize('a:1:{s:7:"message";a:4:{s:2:"to";s:10:"Jack Smith";s:4:"from";s:8:"Jane Doe";s:7:"subject";s:11:"Hello World";s:4:"body";s:24:"Hello, whats going on...";}}');
```

#### Parse YAML

[](#parse-yaml)

```
$parser = new Parser();
$parsed = $parser->yaml('
				---
				message:
				    to: "Jack Smith"
				    from: "Jane Doe"
				    subject: "Hello World"
				    body: "Hello, whats going on..."
				');
```

#### Parse BSON

[](#parse-bson)

```
$parser = new Parser();
$parsed = $parser->bson('BSON DATA HERE');
```

#### Parse MSGPack

[](#parse-msgpack)

```
$parser = new Parser();
$parsed = $parser->msgpack('MSGPACK DATA HERE');
```

Custom Parsers/Formatters
-------------------------

[](#custom-parsersformatters)

You can make your own custom parsers/formatters by implementing [FormatInterface](https://github.com/nathanmac/Parser/blob/master/src/Formats/FormatInterface.php), the below example demostrates the use of a custom parser/formatter.

```
use Nathanmac\Utilities\Parser\Formats\FormatInterface;

/**
 * Custom Formatter
 */

class CustomFormatter implements FormatInterface {
    /**
     * Parse Payload Data
     *
     * @param string $payload
     *
     * @return array
     *
     * @throws ParserException
     */
    public function parse($payload)
    {
        $payload; // Raw payload data

        $output = // Process raw payload data to array

        return $output; // return array parsed data
    }
}
```

### Using the CustomFormatter

[](#using-the-customformatter)

```
use Acme\Formatters\CustomFormatter;

$parser = new Parser();
$parsed = $parser->parse('RAW PAYLOAD DATA', new CustomFormatter());
```

### Autodetecting the CustomFormatter

[](#autodetecting-the-customformatter)

```
use Acme\Formatters\CustomFormatter;

$parser = new Parser();
$parser->registerFormat('application/x-custom-format', 'Acme\Formatters\CustomFormatter');
$parser->payload('application/x-custom-format');
```

Testing
-------

[](#testing)

To test the library itself, run the tests:

```
composer test

```

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Credits
-------

[](#credits)

- [nathanmac](https://github.com/nathanmac)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

Appendix
--------

[](#appendix)

###### Supported Content-Types

[](#supported-content-types)

```
XML
---
application/xml > XML
text/xml > XML

JSON
----
application/json > JSON
application/x-javascript > JSON
text/javascript > JSON
text/x-javascript > JSON
text/x-json > JSON

YAML
----
text/yaml > YAML
text/x-yaml > YAML
application/yaml > YAML
application/x-yaml > YAML

BSON
----
application/bson > BSON

MSGPack
-------
application/msgpack > MSGPack
application/x-msgpack > MSGPack

MISC
----
application/vnd.php.serialized > Serialized Object
application/x-www-form-urlencoded' > Query String

```

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity21

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity69

Established project with proven stability

 Bus Factor1

Top contributor holds 73.6% 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 ~49 days

Recently: every ~148 days

Total

30

Last Release

2952d ago

Major Versions

v1.7 → v2.02014-10-27

v2.3 → v3.02015-05-16

v3.11 → v4.02016-07-28

PHP version history (2 changes)v1.0PHP &gt;=5.2.0

v3.3PHP &gt;=5.3.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/24a9f8096d4e8c6e6d24e1e8aea503b8fa23449ae8583031cc3ea77b1b05b55b?d=identicon)[PeterDKC](/maintainers/PeterDKC)

---

Top Contributors

[![nathanmac](https://avatars.githubusercontent.com/u/3205902?v=4)](https://github.com/nathanmac "nathanmac (39 commits)")[![mubinov](https://avatars.githubusercontent.com/u/962146?v=4)](https://github.com/mubinov "mubinov (5 commits)")[![danhunsaker](https://avatars.githubusercontent.com/u/1534396?v=4)](https://github.com/danhunsaker "danhunsaker (4 commits)")[![scottpnelson](https://avatars.githubusercontent.com/u/3683721?v=4)](https://github.com/scottpnelson "scottpnelson (1 commits)")[![artn](https://avatars.githubusercontent.com/u/195194?v=4)](https://github.com/artn "artn (1 commits)")[![teimos](https://avatars.githubusercontent.com/u/11861981?v=4)](https://github.com/teimos "teimos (1 commits)")[![djereg](https://avatars.githubusercontent.com/u/6384768?v=4)](https://github.com/djereg "djereg (1 commits)")[![matriphe](https://avatars.githubusercontent.com/u/277262?v=4)](https://github.com/matriphe "matriphe (1 commits)")

---

Tags

jsonapixmlparser

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/peterdkc-parser/health.svg)

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

###  Alternatives

[nathanmac/parser

Simple PHP Parser Utility Library for API Development

2151.0M3](/packages/nathanmac-parser)[art4/json-api-client

JSON API client

139791.3k7](/packages/art4-json-api-client)[nilportugues/api-problems

PSR7 Response implementation for the Problem Details for HTTP APIs

1749.4k2](/packages/nilportugues-api-problems)

PHPackages © 2026

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