Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Pretty Xml Laravel Package

simonschaufi/pretty-xml

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require simonschaufi/pretty-xml
    

    No additional configuration is required—just require the package in your PHP file.

  2. 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>
    
  3. First Use Case: Minifying XML

    $minifiedXml = PrettyXml::minify($xmlString);
    echo $minifiedXml;
    

    Output:

    <root><child attr="value">text</child></root>
    
  4. Where to Look First

    • GitHub Repository (if available) – Check for examples, issues, or updates.
    • PrettyXml class methods: pretty(), minify(), and format() (if available).
    • Test edge cases (e.g., malformed XML, namespaces, CDATA).

Implementation Patterns

Common Workflows

  1. 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]);
    
  2. 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);
    
  3. 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]);
    
  4. 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);
    
  5. 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) {}
    

Integration Tips

  • Namespaces: The package handles namespaces by default. Test with complex XML:
    <root xmlns:ns="http://example.com/ns">
        <ns:child>content</ns:child>
    </root>
    
  • CDATA Sections: Preserved during pretty-printing/minifying.
  • Validation: Combine with DOMDocument for validation before processing:
    $dom = new DOMDocument();
    if (!$dom->loadXML($xmlString)) {
        throw new \InvalidArgumentException('Invalid XML');
    }
    $prettyXml = PrettyXml::pretty($dom->saveXML());
    

Gotchas and Tips

Pitfalls

  1. 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');
    }
    
  2. 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.

  3. Performance with Large XML For files >1MB, consider streaming or chunked processing to avoid memory issues.

  4. 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());
    

Debugging Tips

  • Compare Before/After: Use diff tools to compare original vs. pretty/minified XML:
    diff <(echo "$originalXml") <(echo "$prettyXml") | less
    
  • Log Raw Input: Always log the raw XML input before processing to debug issues:
    Log::debug('Raw XML', ['input' => $xmlString]);
    
  • Check for Hidden Characters: Use trim() or preg_replace() to strip BOM/control characters:
    $cleanXml = preg_replace('/[\x00-\x1F]/', '', $xmlString);
    

Extension Points

  1. 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);
        }
    }
    
  2. 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) { /* ... */ }
    }
    
  3. 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);
    

Configuration Quirks

  • No Built-in Config: The package relies on method arguments (e.g., pretty($xml, ['indent' => ' '])). Check the source for available options.
  • Default Indentation: Uses 2 spaces by default. Override via:
    PrettyXml::pretty($xml, ['indent' => "\t"]);
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor