Installation
composer require simonschaufi/pretty-xml
No additional configuration is required—just require the package in your PHP file.
First Use Case: Pretty-Printing XML
use SimonSchaufi\PrettyXml\PrettyXml;
$xmlString = '<root><child attr="value">text</child></root>';
$prettyXml = PrettyXml::pretty($xmlString);
echo $prettyXml;
Output:
<root>
<child attr="value">text</child>
</root>
First Use Case: Minifying XML
$minifiedXml = PrettyXml::minify($xmlString);
echo $minifiedXml;
Output:
<root><child attr="value">text</child></root>
Where to Look First
PrettyXml class methods: pretty(), minify(), and format() (if available).Pretty-Printing API Responses Useful for debugging or logging XML responses from third-party APIs (e.g., SOAP, legacy systems).
$apiResponse = file_get_contents('https://example.com/api.xml');
$formattedResponse = PrettyXml::pretty($apiResponse);
Log::debug('API Response:', ['xml' => $formattedResponse]);
Minifying XML for Storage/Transmission Reduce payload size for storage (e.g., database) or transmission (e.g., HTTP requests).
$minified = PrettyXml::minify($xmlData);
$this->xmlColumn->save($minified);
Dynamic XML Generation with Laravel Blade Pretty-print XML templates in Blade views for readability during development.
// In a controller
$xmlData = '<config>' . PrettyXml::pretty($this->generateConfigXml()) . '</config>';
return view('admin.config', ['xml' => $xmlData]);
Integration with Laravel HTTP Clients Pretty-print responses from Guzzle or Symfony HTTP clients for debugging.
$response = Http::get('https://example.com/feed.xml');
$prettyFeed = PrettyXml::pretty($response->body());
dd($prettyFeed);
Service Provider Binding (Optional)
Bind the PrettyXml class to Laravel’s container for global use:
// In AppServiceProvider
$this->app->bind(PrettyXml::class, function () {
return new \SimonSchaufi\PrettyXml\PrettyXml();
});
Then inject via constructor:
public function __construct(private PrettyXml $prettyXml) {}
<root xmlns:ns="http://example.com/ns">
<ns:child>content</ns:child>
</root>
DOMDocument for validation before processing:
$dom = new DOMDocument();
if (!$dom->loadXML($xmlString)) {
throw new \InvalidArgumentException('Invalid XML');
}
$prettyXml = PrettyXml::pretty($dom->saveXML());
Malformed XML Throws Exceptions The package does not validate XML. Always sanitize input:
try {
$prettyXml = PrettyXml::pretty($userInputXml);
} catch (\Exception $e) {
Log::error('Invalid XML provided', ['error' => $e->getMessage()]);
abort(400, 'Invalid XML format');
}
Whitespace Sensitivity in Minification Minification removes all whitespace, including newlines and indentation. Test with:
<root>
<child> <![CDATA[ text ]]> </child>
</root>
Minified output may collapse CDATA whitespace unpredictably.
Performance with Large XML For files >1MB, consider streaming or chunked processing to avoid memory issues.
Namespace Handling Quirks
Some XML processors (e.g., SimpleXMLElement) may alter namespace declarations. Pretty-print after parsing:
$xml = simplexml_load_string($xmlString);
$dom = dom_import_simplexml($xml);
$prettyXml = PrettyXml::pretty($dom->ownerDocument->saveXML());
diff tools to compare original vs. pretty/minified XML:
diff <(echo "$originalXml") <(echo "$prettyXml") | less
Log::debug('Raw XML', ['input' => $xmlString]);
trim() or preg_replace() to strip BOM/control characters:
$cleanXml = preg_replace('/[\x00-\x1F]/', '', $xmlString);
Custom Formatting Rules
Extend the package by subclassing PrettyXml and overriding methods:
class CustomPrettyXml extends \SimonSchaufi\PrettyXml\PrettyXml {
public function pretty($xml, array $options = []) {
$options['indent'] = ' '; // Custom indent
return parent::pretty($xml, $options);
}
}
Add Pre/Post-Processing Wrap the package in a decorator pattern for additional logic:
class XmlProcessor {
public function process($xml, bool $prettyPrint) {
$sanitized = $this->sanitize($xml);
return $prettyPrint
? PrettyXml::pretty($sanitized)
: PrettyXml::minify($sanitized);
}
private function sanitize($xml) { /* ... */ }
}
Laravel Facade (Optional) Create a facade for cleaner syntax:
// app/Facades/Xml.php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
class Xml extends Facade {
protected static function getFacadeAccessor() {
return \SimonSchaufi\PrettyXml\PrettyXml::class;
}
}
Usage:
use App\Facades\Xml;
Xml::pretty($xmlString);
pretty($xml, ['indent' => ' '])). Check the source for available options.PrettyXml::pretty($xml, ['indent' => "\t"]);
How can I help you explore Laravel packages today?