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

Laminas Xml Laravel Package

laminas/laminas-xml

Secure XML utilities for PHP: parse and validate XML with safe defaults, mitigate XXE/XEE attacks, and control external entity loading. Helpful for apps that consume untrusted XML and need hardened DOM/LibXML configuration.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require laminas/laminas-xml:^1.8
    

    Ensure your project supports PHP 8.5 (minimum requirement for this version). Add to composer.json under require if not using Composer globally.

  2. First Use Case: Parsing XML

    use Laminas\Xml\Reader;
    
    $reader = new Reader();
    $reader->open('data.xml');
    
    while ($reader->read()) {
        if ($reader->nodeType === Reader::ELEMENT) {
            echo $reader->name . "\n";
        }
    }
    
  3. Where to Look First

    • Laminas XML Documentation (if available)
    • src/ directory for core classes (Reader, Writer, Dom, Soap, etc.)
    • tests/ for usage examples and edge cases.
    • PHP 8.5 Migration Guide: Check for new type hints or reserved keywords in the codebase.

Implementation Patterns

Common Workflows

  1. XML Parsing with Reader

    • Iterate through nodes, validate structure, and extract data.
    • Example: Scraping API responses or config files.
    $reader = new Reader();
    $reader->open('config.xml');
    
    $config = [];
    while ($reader->read()) {
        if ($reader->nodeType === Reader::ELEMENT && $reader->depth === 1) {
            $config[$reader->name] = $reader->readString();
        }
    }
    
  2. Generating XML with Writer

    • Build XML dynamically for APIs, reports, or configs.
    • Example: Creating a SOAP envelope or RSS feed.
    $writer = new Writer();
    $writer->openMemory();
    $writer->startElement('root');
    
    $writer->writeElement('title', 'Sample');
    $writer->writeElement('author', 'Laminas');
    
    $writer->endElement();
    $xml = $writer->saveXML();
    
  3. DOM Manipulation

    • Use Laminas\Xml\Dom for complex XML transformations.
    • Example: Modifying Laravel config files or XSLT processing.
    $dom = new \Laminas\Xml\Dom('data.xml');
    $nodes = $dom->getElementsByTagName('item');
    foreach ($nodes as $node) {
        $node->setAttribute('processed', 'true');
    }
    
  4. SOAP Integration

    • Handle SOAP requests/responses securely.
    • Example: Consuming a third-party SOAP API.
    use Laminas\Xml\Soap\Client;
    
    $client = new Client('http://example.com/soap?wsdl');
    $response = $client->__soapCall('getData', [$params]);
    
  5. Validation and Security

    • Sanitize XML input to prevent XXE or DoS attacks.
    • Example: Disabling external entity loading.
    $reader = new Reader();
    $reader->setOptions([
        Reader::OPTION_DISABLE_EXTERNAL_ENTITIES => true,
    ]);
    $reader->open('user-uploaded.xml');
    

Integration Tips

  • Laravel Service Providers: Bind Laminas\Xml\* interfaces to Laravel’s container for dependency injection.
    $this->app->bind(\Laminas\Xml\Reader::class, function () {
        return new \Laminas\Xml\Reader();
    });
    
  • Middleware: Validate XML payloads in incoming requests (e.g., API endpoints).
  • Artisan Commands: Process XML files in bulk (e.g., import/export tools).
  • Events: Trigger events when XML parsing succeeds/fails (e.g., log malformed XML).
  • PHP 8.5 Features: Leverage new features like read-only properties or enums if extending the package.

Gotchas and Tips

Pitfalls

  1. XXE Vulnerabilities

    • Always disable external entities unless explicitly needed:
      $reader->setOptions([Reader::OPTION_DISABLE_EXTERNAL_ENTITIES => true]);
      
    • Avoid loading untrusted XML files directly into DOM.
  2. Memory Limits

    • Large XML files may exceed PHP’s memory_limit. Use Reader for streaming:
      $reader->open('large-file.xml');
      while ($reader->read()) { /* Process incrementally */ }
      
  3. Namespace Handling

    • Namespaces in XML can break simple queries. Use DomXPath for robust queries:
      $xpath = new \DomXPath($dom);
      $nodes = $xpath->query('//ns:item', $dom->ownerDocument);
      
  4. SOAP Quirks

    • SOAP clients may require WSDL caching or custom headers:
      $client = new Client('wsdl.url', [
          'cache_wsdl' => WSDL_CACHE_NONE,
          'trace' => 1,
      ]);
      
  5. Encoding Issues

    • XML declarations may cause UTF-8 headaches. Normalize output:
      $writer->openMemory();
      $writer->writeDeclaration('1.0', 'UTF-8');
      
  6. PHP 8.5 Compatibility

    • Reserved Keywords: Ensure no conflicts with new PHP 8.5 reserved keywords (e.g., match, fn).
    • Type System: Verify custom extensions or overrides align with PHP 8.5’s stricter typing.

Debugging Tips

  • Enable Reader Debugging
    $reader->setOptions([Reader::OPTION_DEBUG => true]);
    
  • Validate XML Structure Use Laminas\Xml\Validator or xmllint CLI tool:
    xmllint --noout --schema schema.xsd data.xml
    
  • Check for Well-Formedness Wrap parsing in a try-catch:
    try {
        $reader->open('data.xml');
    } catch (\Laminas\Xml\Exception\RuntimeException $e) {
        Log::error('XML error: ' . $e->getMessage());
    }
    

Extension Points

  1. Custom Writers/Readers Extend Laminas\Xml\Writer or Reader for domain-specific logic:

    class MyXmlWriter extends \Laminas\Xml\Writer {
        public function writeCustomElement(string $name, array $data) {
            $this->startElement($name);
            foreach ($data as $key => $value) {
                $this->writeElement($key, $value);
            }
            $this->endElement();
        }
    }
    
  2. Event Dispatching Integrate with Laravel Events for XML lifecycle hooks:

    event(new XmlParsed($reader, $data));
    
  3. Caching Parsed XML Cache DomDocument or parsed arrays to avoid reprocessing:

    $cacheKey = 'xml_data_' . md5($filePath);
    $data = Cache::remember($cacheKey, 3600, function () use ($reader) {
        return $this->parseXml($reader);
    });
    
  4. Testing Mock Reader/Writer in PHPUnit for isolated tests:

    $mockReader = $this->createMock(\Laminas\Xml\Reader::class);
    $mockReader->method('read')->willReturnOnConsecutiveCalls(
        ['nodeType' => \Laminas\Xml\Reader::ELEMENT, 'name' => 'test']
    );
    
  5. PHP 8.5 Optimizations

    • Use named arguments for clarity in method calls.
    • Adopt constructor property promotion in custom extensions.
    • Leverage attributes for dependency injection in new classes.
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