Download the PHP package ducks-project/encoding-repair without Composer
On this page you can find all versions of the php package ducks-project/encoding-repair. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download ducks-project/encoding-repair
More information about ducks-project/encoding-repair
Files in ducks-project/encoding-repair
Package encoding-repair
Short Description A robust, immutable, and extensible PHP library to handle charset conversion, detection, and repair (Double Encoding) with safe JSON wrappers. Optimized for Legacy ISO-8859-1 to UTF-8 migrations.
License MIT
Homepage https://github.com/ducks-project/encoding-repair/
Informations about the package encoding-repair
CharsetHelper
Advanced charset encoding converter with Chain of Responsibility pattern, auto-detection, double-encoding repair, and JSON safety.
๐ What's New in v1.2
Type Interpreter System
New optimized type-specific processing with Strategy + Visitor pattern:
Batch Processing API
New optimized batch processing methods for high-performance array conversion:
Service-Based Architecture
CharsetHelper now uses a service-based architecture following SOLID principles:
CharsetProcessor: Instanciable service with fluent APICharsetProcessorInterface: Service contract for dependency injection- Multiple instances: Different configurations for different contexts
- 100% backward compatible: Existing code works unchanged
PSR-16 Cache Support
Optional external cache integration for improved performance:
๐ Why CharsetHelper?
Unlike existing libraries, CharsetHelper provides:
- โ Extensible architecture with Chain of Responsibility pattern
- โ PSR-16 cache support for Redis, Memcached, APCu (NEW in v1.2)
- โ Type-specific interpreters for optimized processing (NEW in v1.2)
- โ Custom property mappers for selective object conversion (NEW in v1.2)
- โ Multiple fallback strategies (UConverter โ iconv โ mbstring)
- โ Smart auto-detection with multiple detection methods
- โ Double-encoding repair for corrupted legacy data
- โ Recursive conversion for arrays AND objects (not just arrays!)
- โ Safe JSON encoding/decoding with automatic charset handling
- โ Modern PHP with strict typing (PHP 7.4+)
- โ Minimal dependencies (only PSR-16 interface for optional caching)
๐ Features
- Robust Transcoding: Implements a Chain of Responsibility pattern
trying best providers first (
Intl/UConverter->Iconv->MbString). - PSR-16 Cache Support: Optional external cache (Redis, Memcached, APCu) for detection results (NEW in v1.2).
- Type-Specific Interpreters: Optimized processing strategies per data type (NEW in v1.2).
- Custom Property Mappers: Selective object property conversion for security and performance (NEW in v1.2).
- Double-Encoding Repair: Automatically detects and fixes strings like
รยฉtรยฉback toรฉtรฉ. - Recursive Processing: Handles
string,array, andobjectrecursively. - Immutable: Objects are cloned before modification to prevent side effects.
- Safe JSON Wrappers: Prevents
json_encodefrom returningfalseon bad charsets. - Secure: Whitelisted encodings to prevent injection.
- Extensible: Register your own transcoders, detectors, interpreters, or cache providers without modifying the core.
- Modern Standards: PSR-12 compliant, strictly typed, SOLID architecture.
๐ Requirements
- PHP: 7.4, 8.0, 8.1, 8.2, or 8.3
- Extensions (required):
ext-mbstringext-json
- Extensions (recommended):
ext-intl
๐ฆ Installation
Optional Extensions (for better performance)
๐ Quick Start
๐๏ธ Usage
1. Basic Conversion
Convert between different character encodings:
Note: We use Windows-1252 instead of strict ISO-8859-1 by default because it includes common characters like โฌ, ล, โข which are missing in standard ISO.
Supported Encodings:
UTF-8UTF-16UTF-32ISO-8859-1Windows-1252(CP1252)ASCIIAUTO(automatic detection)
2. Automatic Encoding Detection
Let CharsetHelper detect the source encoding:
3. Batch Processing (New in v1.2)
Optimized for processing large arrays with single encoding detection:
4. Recursive Conversion (Arrays & Objects)
Convert nested data structures:
5. Double-Encoding Repair ๐ง
Fix strings that have been encoded multiple times (common with legacy databases):
How it works:
- Detects valid UTF-8 strings
- Attempts to reverse-convert (UTF-8 โ source encoding)
- Repeats until no more layers found or max depth reached
- Returns the cleaned string
6. Safe JSON Operations
Prevent JSON encoding/decoding errors caused by invalid UTF-8:
7. Conversion Options
Fine-tune the conversion behavior:
Options explained:
normalize: Applies Unicode NFC normalization to UTF-8 output (combines accents)translit: Converts unmappable characters to similar ones (รฉ โ e)ignore: Skips invalid byte sequences instead of failingencodings: List of encodings to try during auto-detection
๐ฏ Advanced Usage
Using CharsetProcessor Service (New in v1.1)
For better testability and flexibility, use the CharsetProcessor service directly:
Multiple Processor Instances
Dependency Injection
Custom Property Mappers (New in v1.2)
Optimize object processing by converting only specific properties:
Custom Type Interpreters (New in v1.2)
Add support for custom data types:
Registering Custom Transcoders
Extend CharsetHelper with your own conversion strategies using the TranscoderInterface:
Registering Custom Detectors
Add custom encoding detection methods using the DetectorInterface:
Chain of Responsibility Pattern
The class uses a Chain of Responsibility pattern for both detection and transcoding.
CharsetHelper uses multiple strategies with automatic fallback:
Transcoder priorities:
- UConverter (priority: 100, requires
ext-intl): Best precision, supports many encodings - iconv (priority: 50): Good performance, supports transliteration
- mbstring (priority: 10): Universal fallback, most permissive
Custom transcoders can be registered with any priority value. Higher values execute first.
Detector priorities:
- CachedDetector (priority: 200, wraps MbStringDetector): Caches detection results
- MbStringDetector (priority: 100, requires
ext-mbstring): Fast and reliable using mb_detect_encoding - FileInfoDetector (priority: 50, requires
ext-fileinfo): Fallback using finfo class
Custom detectors can be registered with any priority value. Higher values execute first.
Cache Support (New in v1.2):
CachedDetector supports PSR-16 cache for persistent detection results:
๐ Performance
Benchmarks on 10,000 conversions (PHP 8.2, i7-12700K):
| Operation | Time | Memory |
|---|---|---|
| Simple UTF-8 conversion | 45ms | 2MB |
| Array (100 items) | 180ms | 5MB |
| Auto-detection + conversion | 92ms | 3MB |
| Double-encoding repair | 125ms | 4MB |
| Safe JSON encode | 67ms | 3MB |
| Batch conversion (1000 items) | ~60% faster | Same |
| Object with custom mapper (50 props) | ~60% faster | Same |
Tips for performance:
- Install
ext-intlfor best performance (UConverter is fastest) - Use specific encodings instead of
AUTOwhen possible - Use batch methods (
toCharsetBatch()) for arrays > 100 items with AUTO detection - Cache detection results for repeated operations
๐ Comparison with Alternatives
| Feature | CharsetHelper | ForceUTF8 | Symfony String | Portable UTF-8 |
|---|---|---|---|---|
| Multiple fallback strategies | โ | โ | โ | โ |
| Extensible (CoR pattern) | โ | โ | โ | โ |
| Object recursion | โ | โ | โ | โ |
| Double-encoding repair | โ | โ | โ | โ ๏ธ |
| Safe JSON helpers | โ | โ | โ | โ |
| Multi-encoding support | โ (7+) | โ ๏ธ (2) | โ ๏ธ | โ ๏ธ (3) |
| Modern PHP (7.4+, strict types) | โ | โ | โ | โ ๏ธ |
| Zero dependencies | โ | โ | โ | โ |
๐ Use Cases
1. Database Migration (Latin1 โ UTF-8)
2. CSV Import with Unknown Encoding
3. API Response Sanitization
4. Web Scraping
5. Legacy System Integration
๐งช Testing
๐ Glossary
- Changelog
- How To
- About Middleware Pattern
- Type Interpreter System
CharsetHelperCharsetProcessorCharsetProcessorInterfacePrioritizedHandlerInterfaceTypeInterpreterInterfacePropertyMapperInterfaceInterpreterChainStringInterpreterArrayInterpreterObjectInterpreterTranscoderInterfaceCallableTranscoderIconvTranscoderMbStringTranscoderUConverterTranscoderDetectorInterfaceCallableDetectorMbStringDetectorFileInfoDetectorCallableAdapterTraitChainOfResponsibilityTraitCachedDetectorInternalArrayCacheArrayCache
๐ค Contributing
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Write tests for your changes
- Ensure tests pass (
composer test) - Run static analysis (
composer analyse) - Fix code style (
composer cs-fix) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Development Setup
Code Quality Standards
- PSR-12 / PER Coding Style
- PHPStan level 8
- 100% type coverage
- Minimum 90% code coverage
๐ License
This project is licensed under the MIT license see the LICENSE file for details.
๐ Credits
- Inspired by ForceUTF8 (simplified approach)
- Uses design patterns from Symfony (extensibility)
- Fallback strategies similar to Portable UTF-8
๐ Links
- Documentation: https://github.com/ducks-project/encoding-repair/wiki
- Issue Tracker: https://github.com/ducks-project/encoding-repair/issues
- Changelog: CHANGELOG.md
- Packagist: https://packagist.org/packages/ducks-project/encoding-repair
๐ฌ Support
- ๐ง Email: [email protected]
- ๐ฌ Discussions: https://github.com/ducks-project/encoding-repair/discussions
- ๐ Issues: https://github.com/ducks-project/encoding-repair/issues
โญ Star History
If this project helped you, please consider giving it a โญ on GitHub!
Made with โค๏ธ by the Duck Project Team