Skip to content
A PHP library for compacting the contents of files.
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
Failed to load latest commit information.


Build Status Coverage Status Latest Stable Version Total Downloads

A PHP library for compacting the contents of files.



Via Composer:

$ composer require "phine/compact=~1.0"


The Compact library provides a consistent way of compacting files and their contents. The purpose of the library is simply to reduce the size of the contents without affecting how it is used. For example, compacting a JSON file would involve removing any excess whitespace that was used for "pretty printing".

use Phine\Compact\Json;

$compactor = new Json();

echo $compactor->compactFile('example.json');

// which is also the same as

echo $compactor->compactContents(file_get_contents('example.json'));

Assuming we had this in example.json:

    "name": 123

The contents would then be compacted to:


Bundled Compactors

The library also includes the following compactor classes:

  • Phine\Compact\Json — For compacting JSON files.
  • Phine\Compact\Php — For compacting PHP files.
  • Phine\Compact\Xml — For compacting XML files.

Creating a Compactor

The library includes an interface that all bundled classes implement. An abstract class is also included, which all bundled compactor classes extend. When you create your own compactor class, you will want to extend the Phine\Compact\AbstractCompact class.

use Phine\Compact\AbstractCompact;

 * Simply trims all lines.
class Trim extends AbstractCompact
     * {@inheritDoc}
    public function compactContents($contents)
        $contents = preg_replace('/^\s+/m', '', $contents);
        $contents = preg_replace('/\s+$/m', '', $contents);

        return $contents;

When extending the AbstractCompact class, the compactFile() method will already be implemented for you. It will rely on the compactContents() method to compact the contents after it has been read from the file.

Please considering adding your compactor class to the wiki.


If you need to manage multiple compactors, the library offers a Collection class. In addition to the class, an interface is provided so that different implementations can be supported.

use Phine\Compact\Collection;
use Phine\Compact\Json;
use Phine\Compact\Php;
use Phine\Compact\Xml;

$collection = new Collection();
$collection->addCompactor(new Json());
$collection->addCompactor(new Php());
$collection->addCompactor(new Xml());

$json = <<<JSON
    "key": "value"

echo $collection->getCompactor('json')->compactContents($json);
// {"key":"value"}


You can find the API documentation here.


This library is available under the MIT license.

You can’t perform that action at this time.