PHPackages                             realshadow/serializers - 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. realshadow/serializers

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

realshadow/serializers
======================

PHP collection of serializers for JSON, JSONP, XML, YAML, INI

1.0(10y ago)38MITPHPPHP &gt;=5.3.0

Since Dec 18Pushed 10y ago1 watchersCompare

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

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

PHP collection of serializers for JSON, JSONP, XML, YAML, INI
=============================================================

[](#php-collection-of-serializers-for-json-jsonp-xml-yaml-ini)

Written for PHP 5.3 to solve a specific issue - **singularization/pluralization** of elements when transforming them from and to arrays. The difference between serializers was obvious when we passed XML files between PHP, Python and .NET. Later, more serializers were added to get a complete package.

The goal was to automatically perform singularization of arrays when serializing to XML. E.g.

```
array(
	'products' => array(
	    array(
	        'brand' => 'Samsung',
	        'model' => 'Galaxy',
	        'price' => 999
	    ),
	    array(
	        'brand' => 'HTC',
	        'model' => 'One',
	        'price' => null
	    )
	)
);
```

Which, when serialized, would become

```

   Samsung
   Galaxy
   999

   HTC
   One

```

instead of (this is the default behaviour)

```

   Samsung
   Galaxy
   999

   HTC
   One

```

Same rule applies to deserialization which, by using different serializers, would turn into into different arrays. By applying singularization the other way around, it is possible to **get back the same array** as was used for serialization.

### XML Serialization

[](#xml-serialization)

Support for

- attributes, namespaces, cdata and comments
- singularization of words - products =&gt; product
- option to automatically add xsi:nil=true to null elements
- event for manipulation of nodes

```
$array = array(
	Serializers\Encoders\Xml::ATTRIBUTES => array(
		'xmlns' => 'http://cfh.sk/izmluvnik/xsell',
		Serializers\Encoders\Xml::NS => array(
			array(
				'name' => 'xmlns:xsi',
				'content' => 'http://www.w3.org/2001/XMLSchema-instance'
			),
			array(
				'name' => 'xmlns:xsd',
				'content' => 'http://www.w3.org/2001/XMLSchema'
			)
		)
	),
	'products' => array(
	    array(
	        'brand' => 'Samsung',
	        'model' => 'Galaxy',
	        'price' => 999
	    ),
	    array(
	        'brand' => 'HTC',
	        'model' => 'One',
	        'price' => null
	    )
	)
);

$xml = Serializers\Encode::toXml('root', $array, array(
    'singularize_words' => true,
    'nil_on_null' => true
));

print $xml->withHeaders();
```

Which outputs

```

   Samsung
   Galaxy
   999

   HTC
   One

```

### XML Deserialization

[](#xml-deserialization)

By default every comment, attribute, namespace will be stripped from the result as well as the root element. Every option can be turned off/on in config

Deserialization is done by SimpleXML coupled with json\_encode (in this case provided JSON decoder) with one simple addition - SimpleXML object will be transformed before being encoded with json\_encode (backport of JSONSerialize interface)

Comments are parsed separately via DOMXpath (since SimpleXML can not handle them) and are added to a separate array with indexes poiting to their original location, with that, it should be easy to merge comments with the main result and receive the original array.

By default, transforming elements from their singular counterpart back to plural and thus flattening the whole array is turned off and must be turned on. Its possible to both - include new mappings for words and to exclude specific words. This works exactly as in provided XML encoder.

The whole goal of flattening is to get back **exactly** the same array as the one that was used to create provided XML.

```
// using the same XML that we got in serialization
$output = Serializers\Decode::xml($xml->load(), array('singularize_words' => true));
```

Which outputs **exactly the same array** as was used in the example before

```
print_r($output->toArray());
```

### JSON Deserialization

[](#json-deserialization)

Support for:

- automatic parsing of Microsoft's JSON date format (e.g. `/Date(1425556377427+0100)/`)
- backport of `JSON_BIGINT_AS_STRING` available from PHP 5.4.0
- isValid method for checking validity of provided JSON string
- possible conversion from JSON to:
    - PHP types (string, array, object)
    - XML, YAML, INI

With overriding configuration one can change the default timeformat and timezone settings form MS date conversion, or turn it off completely.

It's possible to register an event callback to be called during escaping of BIGINT, in case said escaping is not good enough, or to turning it off completely.

Callback method must accept one parameter and thats registered JSON string. Callback can be a closure or anything else that will pass as callable.

```
$json = withHeaders();

// events

$json = Serializers\Decode::json($json)->on(Serializers\Events::JSON_MSDATE_MATCH, function($date) {
    // matches returned from preg_replace_callback
    list(, $timestamp,,) = $date;

    return date('Y-m-d H:i:s', $timestamp);
});
```

### JSON Serialization

[](#json-serialization)

It is possible to register JSON\_SERIALIZE event that works exactly like PHP 5.4 `JsonSerializable` interface and thus allows modifying the object before it is converted to JSON.

JSON Serializer also includes a method for creating dates in Microsoft JSON date format, e.g `/Date(1425556377427+0100)/`

```
$json = Serializers\Encode::toJson(array(
    'foo' => 'bar',
    'foodate' => date('d.m.Y H:i:s')
))->onSerialize(function($data) {
    $data['foodate'] = Serializers\Encoders\Json::toMSDate($data['foodate']);

    return $data;
});

print $json->withHeaders();
```

### JSONP Serialization

[](#jsonp-serialization)

Class for easy JSONP serialization, behaves like JSON serializer with additional checks for callback function name validation, which can be changed with custom event

```
$jsonp = Serializers\Encode::toJsonp('_foo.bar', array(
    'foo' => 'bar',
    'bar' => 'foo'
));

$jsonp->allowCors('*', array('GET', 'POST'));

print $jsonp->withHeaders();
```

### JSONP Deserialization

[](#jsonp-deserialization)

Class for easy JSONP deserialization, behaves like JSON deserializer

```
$json = '_foo.bar({"foo":"bar","bar":"foo"})';

$data = Serializers\Decode::jsonp($json);

print_r($data->toObject());

// transform said json to xml with callback name as root element and output it

print Serializers\Decode::jsonp($json)->toXml()->withHeaders();
```

### YAML Serializer

[](#yaml-serializer)

Uses Symfony's YAML component under the hood

```
$yaml = \Serializers\Encode::toYaml($array);

print_r($yaml->load());

// or

$yaml->toFile('config.yml');
```

### YAML Deserializer

[](#yaml-deserializer)

Uses Symfony's YAML component under the hood.

Transformation to `XML`, `JSON`, etc. is possible, but is subjected to the possibilities of the YAML converter.

```
$yaml = Serializers\Decode::yaml(file_get_contents('config.yml'));

print_r($yaml->toObject());

// transform said json to xml and output it

print Serializers\Decode::yaml(file_get_contents('config.yml'))->toXml('yaml')->withHeaders();
```

### INI Deserializer

[](#ini-deserializer)

Uses INI parser by @austinhyde

```
$array = array(
	'a' => 'd',
	'b' => array('test' => 'c'),
	'database' => array(
		'default' => array(
			'name' => 'db',
			'host' => 'master.db',
			'ip' => 'dd',
		)
	),
	'array' => array('a', '1', 3),
);

$encode = Serializers\Encode::toIni($array);
$encode->toFile('config.ini');
```

### INI Serializer

[](#ini-serializer)

The functionality is limited to basic INI formats, e.g. no support for inheritance. As I can't see a good use case at the moment, this class is here only for keeping a complete stack of encoders/decoders together

```
$ini = Serializers\Encode::toIni($array);

print_r($ini->load());
```

###  Health Score

25

—

LowBetter than 37% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity8

Limited adoption so far

Community4

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

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

3804d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/f031a679e7413a3d8be4b8f345524670bd0510b7e13ffbafc33a13b54bdf64c3?d=identicon)[realshadow](/maintainers/realshadow)

---

Tags

deserializationjson-serializationjsonpphpserializationxmlxml-serializationyamlconfiguration

### Embed Badge

![Health badge](/badges/realshadow-serializers/health.svg)

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

###  Alternatives

[hassankhan/config

Lightweight configuration file loader that supports PHP, INI, XML, JSON, and YAML files

97513.5M170](/packages/hassankhan-config)[m1/vars

Vars is a simple to use and easily extendable configuration loader with in built loaders for ini, json, PHP, toml, XML and yaml/yml file types. It also comes with in built support for Silex and more frameworks to come soon.

69124.2k1](/packages/m1-vars)[romanpitak/nginx-config-processor

Nginx configuration files processor.

7235.3k1](/packages/romanpitak-nginx-config-processor)[thewunder/conphigure

Framework Agnostic Configuration Library

3115.9k](/packages/thewunder-conphigure)

PHPackages © 2026

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