PHPackages                             matheusab/php-js-pretty-printer - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. matheusab/php-js-pretty-printer

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

matheusab/php-js-pretty-printer
===============================

1.1(2y ago)125.0k—9.6%MITPHPPHP &gt;=7.4

Since Sep 9Pushed 2y ago1 watchersCompare

[ Source](https://github.com/matheusab-soft/php-js-pretty-printer)[ Packagist](https://packagist.org/packages/matheusab/php-js-pretty-printer)[ RSS](/packages/matheusab-php-js-pretty-printer/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (4)DependenciesVersions (5)Used By (0)

php-js-pretty-printer
=====================

[](#php-js-pretty-printer)

This project allows you to "prettily" generate JS syntax (separators and line breaks included) through PHP classes.

It differs from [json\_encode](https://www.php.net/manual/en/function.json-encode.php) due to its capability of printing **raw js** as well as strings.

Installation
============

[](#installation)

Include it via Composer:

```
composer require matheusab/php-js-pretty-printer

```

Usage
=====

[](#usage)

Let's suppose you need to print a javascript object that contains strings, functions, arrays and objects as values. You can do it like so:

```
use MAB\JS\JS;

$js = JS::object([
    'string'  => 'myStringValue',
    'rawJS'   => JS::raw("() => {}"),
    'array1'  => [1, 2, 3],
    'array2'  => JS::array(1, 2, 3), // same as array1
    'array3'  => JS::array(1, 2, 3)->breakLine(),
    'object1' => [
        'a' => 1,
        'b' => 2
    ],
    'object2' => JS::object([ //same as object1
        'a' => 1,
        'b' => 2
    ]),
]);

echo $js;
```

Result:

```
{
    "myString": "myStringValue",
    "myCallback": () => {},
    "array1": [1, 2, 3],
    "array2": [1, 2, 3],
    "array3": [
        1,
        2,
        3
    ],
    "object1": {
        "a": 1,
        "b": 2
    },
    "object2": {
        "a": 1,
        "b": 2
    }
}
```

API
---

[](#api)

Through the main class, `JS`, you have access to the following creational methods:

MethodArgumentsReturn type`format``array $lines, int $level = 0`string`array``...$items`JSArray`object``?array $object = []`JSObject`raw``string $js`RawFormatting
----------

[](#formatting)

Call `->format()` on a `JSArray` or `JSObject` or use `JS::format($lines)`, like so:

```
