PHPackages                             anhoder/pretty-dumper - 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. [Debugging &amp; Profiling](/categories/debugging)
4. /
5. anhoder/pretty-dumper

ActiveLibrary[Debugging &amp; Profiling](/categories/debugging)

anhoder/pretty-dumper
=====================

PHP debugging output dumper tools for CLI and web

v1.1.2(3mo ago)13MITPHPPHP ^8.0

Since Feb 10Pushed 3mo agoCompare

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

READMEChangelogDependencies (2)Versions (5)Used By (0)

Pretty Dumper
=============

[](#pretty-dumper)

**Powerful PHP debugging output tool for CLI and Web environments**

[![PHP Version](https://camo.githubusercontent.com/6da9704adc310b64eea60cc463a5e5c8dd738da86ba6c3e2af0cfd4600621755/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e302d626c75652e737667)](https://www.php.net/)[![License](https://camo.githubusercontent.com/8bb50fd2278f18fc326bf71f6e88ca8f884f72f179d3e555e20ed30157190d0d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e2e737667)](LICENSE)[![Tests](https://camo.githubusercontent.com/f82f690f486d306dae8d3e4e33f0eb2d79a2cba168b7b6d7fe098ce29c31014a/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f74657374732d706573742d6666363962342e737667)](https://pestphp.com/)

Introduction
------------

[](#introduction)

Pretty Dumper is a modern PHP debugging library that provides highly readable output for variables, exceptions, and stack traces. It supports both CLI colored output and Web HTML rendering, making debugging more efficient and intuitive.

### ✨ Core Features

[](#-core-features)

- 🎨 **Dual-Mode Rendering** - CLI colored output &amp; Web HTML interface
- 🌓 **Theme System** - Built-in light/dark themes with auto-switching
- 🔍 **Depth Control** - Smart recursive rendering with circular reference detection
- 🛡️ **Sensitive Data Protection** - Auto-redaction of passwords, tokens, etc.
- 🚀 **High Performance** - Renders 1M elements in ≤ 3 seconds
- ♿ **Accessibility** - WCAG AA compliant
- 🔗 **Framework Integration** - Native Laravel and Symfony support
- 💎 **Advanced Features**:
    - Complete exception chain display
    - SQL auto-detection and beautification
    - JSON auto-parsing and display
    - Diff comparison functionality
    - Context snapshot capture

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

[](#installation)

```
composer require anhoder/pretty-dumper --dev
```

**Requirements**: PHP ^8.0

Quick Start
-----------

[](#quick-start)

### Global Functions

[](#global-functions)

```
// Basic usage
pretty_dump($variable);

// Shorthand
pd($variable);

// Dump multiple variables
dump($var1, $var2, $var3);

// Dump and die
dd($variable);

// Dump with options
pretty_dump($variable, [
    'maxDepth' => 5,
    'maxItems' => 100,
    'theme' => 'dark'
]);

// JSON format output (auto-detects and formats JSON)
dumpj($variable);
pdj($variable);     // JSON format with more options
ddj($variable);     // Dump and die with JSON format
```

### CLI Command Line

[](#cli-command-line)

```
# Basic colored output
pretty-dump --depth=4 "config('app')"

# JSON format output
pretty-dump --format=json 'json_encode(["id" => 42])'

# Read from stdin
echo '{"ok":true}' | pretty-dump --stdin --from=json

# Execute PHP file
pretty-dump --file=bootstrap/cache/inspect.php --depth=6

# Custom theme and indentation
pretty-dump --theme=dark --indent-style=tabs --depth=5 "\$data"
```

### API Usage

[](#api-usage)

```
use Anhoder\PrettyDumper\Formatter\PrettyFormatter;
use Anhoder\PrettyDumper\Renderer\CliRenderer;
use Anhoder\PrettyDumper\Formatter\FormatterConfiguration;

// Create configuration
$config = new FormatterConfiguration([
    'maxDepth' => 5,
    'maxItems' => 200,
    'stringLengthLimit' => 1000,
    'theme' => 'auto'
]);

// Create formatter and renderer
$formatter = PrettyFormatter::forChannel('cli', $config);
$renderer = new CliRenderer($formatter);

// Render output
echo $renderer->render($value);
```

Configuration Options
---------------------

[](#configuration-options)

### FormatterConfiguration Parameters

[](#formatterconfiguration-parameters)

ParameterTypeDefaultDescription`maxDepth`intCLI: 6
Web: 10Maximum depth for object expansion`maxItems`intCLI: 500
Web: 5000Maximum items to display in arrays/objects`stringLengthLimit`int500000String length limit (bytes)`theme`string'auto'Theme: auto/light/dark`redactionRules`arraySee belowSensitive data redaction rules`indentStyle`string'spaces'Indentation style: spaces/tabs`indentSize`intCLI: 0
Web: 2Indentation size`autoDetectJson`boolfalseAuto-detect and format JSON strings`showPerformanceMetrics`boolfalseShow rendering time and statistics### CLI Command Options

[](#cli-command-options)

```
--help                     Show help information
--depth=N                  Object expansion depth
--format=json|cli          Output format
--theme=light|dark|auto    Theme selection
--color / --no-color       Enable/disable colors
--stdin                    Read from stdin
--file=PATH                Read from file
--from=php|json|raw        Input format
--max-items=N              Maximum items limit
--string-limit=N           String length limit
--expand-exceptions        Expand exception details
--show-context             Show context information
--indent-style=spaces|tabs Indentation style
--indent-size=N            Indentation size

```

### Sensitive Data Redaction

[](#sensitive-data-redaction)

Default redaction rules (case-insensitive field name matching):

```
[
    'password',
    'passwd',
    'pwd',
    'secret',
    'token',
    'api_key',
    'apikey',
    'access_token',
    'refresh_token',
    'private_key',
    'auth'
]
```

Custom redaction rules:

```
$config = new FormatterConfiguration([
    'redactionRules' => [
        'creditCard',
        'ssn',
        'phoneNumber'
    ]
]);
```

### Auto-Detection Features

[](#auto-detection-features)

Pretty Dumper automatically detects and formats special data types:

#### SQL Auto-Detection ✨

[](#sql-auto-detection-)

SQL queries are automatically detected and beautified:

```
// Automatic detection - just dump the SQL string
$sql = "SELECT u.id, u.name FROM users u WHERE u.status = 'active' ORDER BY u.created_at DESC";
pd($sql);  // Automatically detected as SQL, formatted and highlighted!

// Works with complex queries too
$complexSql = "SELECT u.id, o.id FROM users u JOIN orders o ON u.id = o.user_id";
pd($complexSql);
```

Supports:

- SELECT, INSERT, UPDATE, DELETE queries
- Complex JOIN statements
- Aggregation with GROUP BY and HAVING
- Common Table Expressions (CTE)
- Syntax highlighting for keywords, strings, and numbers
- Works in both CLI and Web environments

#### JSON Auto-Detection

[](#json-auto-detection)

JSON strings can be automatically detected and formatted:

```
// Using dumpj() - auto-detects JSON
$jsonString = '{"users":[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}],"count":2}';
dumpj($jsonString);

// Or with manual option
pd($jsonString, ['autoDetectJson' => true]);

// With shorthand functions
pdj($data);        // JSON format
ddj($data);        // JSON format and die
```

Features:

- Automatic JSON validation
- Syntax highlighting (keys, strings, numbers, booleans)
- Unicode and emoji support
- Nested structure handling
- Graceful fallback for invalid JSON

### Diff Comparison ✨ NEW

[](#diff-comparison--new)

Compare two values and visualize differences:

```
// Basic diff
use Anhoder\PrettyDumper\Formatter\Transformers\DiffTransformer;

$oldData = ['name' => 'John', 'age' => 30];
$newData = ['name' => 'John', 'age' => 31, 'city' => 'NYC'];

pd_diff($oldData, $newData);

// Diff with auto-detected JSON
$oldJson = '{"name":"Bob","age":25,"skills":["PHP"]}';
$newJson = '{"name":"Bob","age":26,"skills":["PHP","JavaScript"]}';
pd_diff($oldJson, $newJson);

// Auto-diff with last value
$value1 = ['count' => 10];
pd_auto_diff($value1);    // Store first value

$value2 = ['count' => 15];
pd_auto_diff($value2);    // Compare with stored value

// Diff and die
pdd_diff($oldData, $newData);
```

Output marks:

- 🟢 Added keys/values
- 🔴 Removed keys/values
- 🟡 Modified values
- ⚪ Unchanged values

### Conditional Dumping ✨ NEW

[](#conditional-dumping--new)

Dump only when conditions are met:

```
// pd_when - dump when condition is true
$data = ['user' => 'Alice', 'status' => 'active'];
pd_when($data, fn($d) => $d['status'] === 'active');

// pd_when with boolean condition
$error = ['code' => 500, 'message' => 'Server error'];
pd_when($error, false);  // Won't dump

// pd_assert - assertion-based dumping
$response = ['status' => 200, 'data' => ['id' => 1]];
pd_assert($response, fn($r) => $r['status'] === 200, 'HTTP status should be 200');

// pd_assert with message
$user = ['name' => 'Bob', 'age' => 25];
pd_assert($user, fn($u) => $u['age'] >= 18, 'User must be an adult');

// Die after assertion
pdd_assert($config, fn($c) => $c['debug'] === true, 'Debug mode must be enabled');

// Die when condition met
pdd_when($criticalError, true);
```

### Dump History ✨ NEW

[](#dump-history--new)

Track and compare values across code execution:

```
// Compare with last dumped value at this location
$value = ['count' => 10];
pd_auto_diff($value);  // First run - just dumps

$value = ['count' => 15];
pd_auto_diff($value);  // Shows diff from previous value

// Clear all history
pd_clear_history();

// Clear specific location
pd_clear_history(__DIR__ . '/script.php:42');
```

Framework Integration
---------------------

[](#framework-integration)

### Laravel

[](#laravel)

Register the service provider in `config/app.php`:

```
'providers' => [
    // ...
    Anhoder\PrettyDumper\Support\Frameworks\LaravelServiceProvider::class,
],
```

Usage:

```
// Via container
app('pretty-dump')($value, ['maxDepth' => 4]);

// Use global functions directly
pd($user);
dd($request->all());
```

### Symfony

[](#symfony)

Register the Bundle in `config/bundles.php`:

```
return [
    // ...
    Anhoder\PrettyDumper\Support\Frameworks\SymfonyBundle::class => ['all' => true],
];
```

### Web Environment

[](#web-environment)

```

Output debug information:

```php
// Auto-detect environment and output
pd($data);

// Or force Web rendering
$formatter = PrettyFormatter::forChannel('web');
$renderer = new WebRenderer($formatter);
echo $renderer->render($data);

```

Advanced Features
-----------------

[](#advanced-features)

### Exception Handling

[](#exception-handling)

```
try {
    throw new \RuntimeException('Database connection failed', 500);
} catch (\Exception $e) {
    pd($e);  // Complete exception chain and stack trace
}
```

Output includes:

- Exception message and code
- Complete exception chain
- Stack trace (with file and line numbers)
- Variable snapshots

### SQL Detection ✨ Automatic

[](#sql-detection--automatic)

SQL queries are automatically detected and beautified:

```
// Just dump SQL - no special function needed!
$sql = "SELECT u.id, u.name FROM users u WHERE u.status = 'active' ORDER BY u.created_at DESC";
pd($sql);  // Auto-detected as SQL and formatted!

// Complex queries work too
$complexSql = "SELECT
    u.id,
    u.name,
    o.id as order_id,
    o.total
FROM users u
INNER JOIN orders o ON u.id = o.user_id
WHERE u.status = 'active'
ORDER BY o.created_at DESC";
pd($complexSql);

// Inside arrays
$data = [
    'user_query' => "SELECT * FROM users WHERE id = ?",
    'order_query' => "SELECT * FROM orders WHERE user_id = ?",
];
pd($data);  // All SQL strings auto-detected
```

Features:

- Automatic detection of SELECT, INSERT, UPDATE, DELETE queries
- Syntax highlighting (keywords, strings, numbers)
- Proper indentation and formatting
- Works seamlessly in both CLI and Web environments
- No configuration needed - works out of the box!

For specialized SQL operations (with bindings, EXPLAIN, etc.), use `pd_sql()`:

```
$sql = "SELECT * FROM users WHERE id = ? AND status = ?";
$bindings = [123, 'active'];
pd_sql($sql, $bindings, $pdo);  // With PDO connection for EXPLAIN
```

### JSON Auto-Detection ✨

[](#json-auto-detection-)

JSON strings can be automatically detected and formatted using `dumpj()` or the `autoDetectJson` option:

```
$jsonString = '{"users":[{"id":1,"name":"Alice"}]}';
dumpj($jsonString);  // Auto-detected as JSON

// Or with manual option
pd($jsonString, ['autoDetectJson' => true]);

// Works in arrays too
$apiResponse = [
    'user_data' => '{"id":1,"name":"Bob"}',
    'config' => '{"theme":"dark","language":"zh"}',
];
pd($apiResponse, ['autoDetectJson' => true]);
```

### Diff Comparison

[](#diff-comparison)

```
use Anhoder\PrettyDumper\Formatter\Transformers\DiffTransformer;

$oldData = ['name' => 'John', 'age' => 30];
$newData = ['name' => 'John', 'age' => 31, 'city' => 'NYC'];

pd(DiffTransformer::diff($oldData, $newData));
```

Output marks:

- 🟢 Added keys/values
- 🔴 Removed keys/values
- 🟡 Modified values
- ⚪ Unchanged values

### Context Snapshots

[](#context-snapshots)

```
use Anhoder\PrettyDumper\Context\ContextSnapshot;
use Anhoder\PrettyDumper\Context\DefaultContextCollector;

$collector = new DefaultContextCollector();
$snapshot = $collector->collect();

pd($snapshot);  // Includes request info, environment variables, stack, etc.
```

Testing
-------

[](#testing)

```
# Run all tests
composer test

# Run specific test group
./vendor/bin/pest --group=performance

# Static code analysis
composer phpstan

# Code style check
composer mago
```

Project Structure
-----------------

[](#project-structure)

```
src/
├── helpers.php              # Global helper functions
└── PrettyDumper/
    ├── Context/             # Context management
    │   ├── ContextSnapshot.php
    │   └── DefaultContextCollector.php
    ├── Formatter/           # Formatting engine
    │   ├── PrettyFormatter.php
    │   ├── FormatterConfiguration.php
    │   └── Transformers/    # Data transformers
    │       ├── ExceptionTransformer.php
    │       ├── JsonTransformer.php
    │       ├── SqlTransformer.php
    │       └── DiffTransformer.php
    ├── Renderer/            # Rendering layer
    │   ├── CliRenderer.php
    │   ├── WebRenderer.php
    │   └── DiffRenderer.php
    ├── Storage/             # Storage engine
    │   ├── MemoryStorage.php
    │   ├── FileStorage.php
    │   └── DumpHistoryStorage.php
    └── Support/             # Support modules
        ├── Frameworks/      # Framework integration
        │   ├── LaravelServiceProvider.php
        │   └── SymfonyBundle.php
        └── Themes/          # Theme system
            ├── ThemeRegistry.php
            └── ThemeProfile.php

public/assets/
├── css/pretty-dump.css      # Web styles
└── js/pretty-dump.js        # Interactive scripts

examples/
└── run-examples.php         # Interactive examples

tests/
└── FeatureTest.php          # Feature tests

```

Performance
-----------

[](#performance)

- ✅ Renders 1M elements in ≤ 3 seconds
- ✅ Automatic circular reference detection
- ✅ Depth and item count protection
- ✅ Large string truncation mechanism

Browser Compatibility
---------------------

[](#browser-compatibility)

Web rendering supports all modern browsers:

- Chrome/Edge 90+
- Firefox 88+
- Safari 14+
- Opera 76+

No-JavaScript environments can use native ``/`` expansion.

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

[](#contributing)

Issues and Pull Requests are welcome!

License
-------

[](#license)

MIT License

---

Made with ❤️ by [anhoder](https://github.com/anhoder)

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance82

Actively maintained with recent releases

Popularity5

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity42

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~2 days

Total

4

Last Release

91d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/27605589?v=4)[anhoder](/maintainers/anhoder)[@anhoder](https://github.com/anhoder)

---

Top Contributors

[![anhoder](https://avatars.githubusercontent.com/u/27605589?v=4)](https://github.com/anhoder "anhoder (25 commits)")

---

Tags

debugdumpdumperphpprettyvar-dumper

###  Code Quality

TestsPest

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/anhoder-pretty-dumper/health.svg)

```
[![Health](https://phpackages.com/badges/anhoder-pretty-dumper/health.svg)](https://phpackages.com/packages/anhoder-pretty-dumper)
```

###  Alternatives

[symfony/stopwatch

Provides a way to profile code

2.8k387.2M918](/packages/symfony-stopwatch)[fruitcake/laravel-debugbar

PHP Debugbar integration for Laravel

19.1k662.9k29](/packages/fruitcake-laravel-debugbar)[spatie/ignition

A beautiful error page for PHP applications.

510147.6M69](/packages/spatie-ignition)[jokkedk/webgrind

Webgrind is a Xdebug profiling web frontend in PHP5. It implements a subset of the features of kcachegrind and installs in seconds and works on all platforms. For quick'n'dirty optimizations it does the job.

3.3k193.0k](/packages/jokkedk-webgrind)[koriym/printo

An object graph visualizer.

1421.8M2](/packages/koriym-printo)[soloterm/dumps

A Laravel command to intercept dumps from your Laravel application.

125285.7k3](/packages/soloterm-dumps)

PHPackages © 2026

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