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

Xml Laravel Package

veewee/xml

Type-safe, declarative XML toolkit for PHP. Includes DOM helpers, safe error handling, memory-safe reader/writer, XML encode/decode, plus XSD and XSLT utilities. Spec-compliance ready for PHP 8.4+, with maintained v3 for older PHP.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Steps
1. **Installation**: Add the package via Composer:
   ```bash
   composer require veewee/xml
  1. First Use Case: Generate a secure XML file with DOCTYPE disallowed:

    use VeeWee\Xml\Writer\Writer;
    use function VeeWee\Xml\Writer\Builder\document;
    use function VeeWee\Xml\Writer\Builder\element;
    use function VeeWee\Xml\Writer\Builder\value;
    use function VeeWee\Xml\Writer\Configurator\disallow_doctype;
    
    $writer = Writer::forFile('output.xml');
    $writer->configure(disallow_doctype());
    $writer->write(
        document('1.0', 'UTF-8',
            element('root', value('Secure XML without DOCTYPE!'))
        )
    );
    

    This creates output.xml with:

    <?xml version="1.0" encoding="UTF-8"?>
    <root>Secure XML without DOCTYPE!</root>
    
  2. Key Files to Explore:

    • docs/writer.md: For XML generation (updated with security configurators).
    • docs/reader.md: For parsing XML.
    • docs/encoding.md: For JSON-like XML encoding/decoding.
    • docs/security.md: New security-focused documentation (hypothetical, but implied by new feature).

Implementation Patterns

Common Workflows

1. Generating Secure XML (New)

use VeeWee\Xml\Writer\Writer;
use function VeeWee\Xml\Writer\Builder\{document, element, value};
use function VeeWee\Xml\Writer\Configurator\disallow_doctype;

$writer = Writer::forFile('secure.xml');
$writer->configure(disallow_doctype()); // Enforce no-DOCTYPE policy
$writer->write(
    document('1.0', 'UTF-8',
        element('data',
            element('item', value('Sensitive Data'))
        )
    )
);

2. Memory-Safe XML Parsing (Updated)

Use the Reader for large XML files with security awareness:

use VeeWee\Xml\Reader\Reader;

$reader = Reader::fromFile('large_file.xml');
foreach ($reader as $node) {
    if ($node->name === 'item' && !$node->hasDoctype()) {
        // Process node (safe from DOCTYPE attacks)
    }
}

3. JSON-like XML Encoding/Decoding (Unchanged)

use function VeeWee\Xml\encoding\{xml_encode, xml_decode};

$data = ['name' => 'John', 'age' => 30];
$xml = xml_encode($data); // Converts to XML string (auto-disallows DOCTYPE if configured)
$decoded = xml_decode($xml); // Converts back to array

4. Namespaced XML with Security (Updated)

use function VeeWee\Xml\Writer\Builder\{element, namespace_attribute, prefixed_element};
use function VeeWee\Xml\Writer\Configurator\disallow_doctype;

$writer = Writer::forFile('namespaced.xml');
$writer->configure(disallow_doctype());
$writer->write(
    element('root',
        namespace_attribute('http://example.com', 'ex'),
        prefixed_element('ex', 'item', value('Secure Test'))
    )
);

5. XSD Schema Validation (Unchanged)

use VeeWee\Xml\XSD\Validator;

$validator = new Validator('schema.xsd');
$isValid = $validator->validate('data.xml');

6. XSLT Transformations (Unchanged)

use VeeWee\Xml\XSLT\Transformer;

$transformer = new Transformer('style.xsl');
$result = $transformer->transform('input.xml');

Integration Tips

Laravel Service Providers (Updated)

Register the package with security defaults in AppServiceProvider:

public function boot()
{
    $this->app->singleton(Writer::class, fn () =>
        Writer::forFile(storage_path('app/xml/output.xml'))
              ->configure(disallow_doctype())
    );
}

Form Request Validation with XML (Updated)

Extend FormRequest to validate XML payloads and enforce security:

use VeeWee\Xml\encoding\xml_decode;
use VeeWee\Xml\Writer\Configurator\disallow_doctype;

public function validateXml()
{
    $xml = $this->input('xml');
    $data = xml_decode($xml);

    // Re-generate XML to enforce DOCTYPE disallowance
    $writer = Writer::inMemory()->configure(disallow_doctype());
    $writer->write($data);
    $secureXml = $writer->map(memory_output());

    return validator(['xml' => $secureXml], ['xml' => 'required|string'])->validate();
}

API Responses (Updated)

Return XML responses in Laravel with security headers:

use VeeWee\Xml\encoding\xml_encode;
use VeeWee\Xml\Writer\Configurator\disallow_doctype;

return response()->xml(
    xml_encode($data),
    200,
    [
        'Content-Type' => 'application/xml',
        'X-Content-Security' => 'no-doctype'
    ]
);

Queue Jobs for XML Processing (Updated)

use VeeWee\Xml\Writer\Writer;
use VeeWee\Xml\Writer\Configurator\disallow_doctype;

class GenerateXmlJob implements ShouldQueue
{
    public function handle()
    {
        $writer = Writer::forFile(storage_path('app/xml/report.xml'))
                        ->configure(disallow_doctype());
        $writer->write($this->buildXmlStructure());
    }
}

Gotchas and Tips

Pitfalls

  1. PHP 8.4+ Requirement for v4+:

    • If using veewee/xml@^4.0, ensure your project runs on PHP 8.4+.
    • For older PHP versions, stick to ^3.3 (supports 8.2-8.5).
  2. Memory-Safe Reader vs. DOM:

    • The Reader is memory-efficient for large files, but lacks DOM traversal methods.
    • Use DOM component for complex XPath queries or DOM manipulation.
  3. Namespaces in XML:

    • Forgetting to declare namespaces with namespace_attribute will cause malformed XML.
    • Prefixed attributes (prefixed_attribute) require the namespace to be declared first.
  4. Raw XML Injection:

    • The raw() builder bypasses escaping. Only use it for trusted content.
  5. Error Handling:

    • The package throws exceptions on malformed XML. Wrap calls in try-catch:
      try {
          $validator->validate('data.xml');
      } catch (XmlException $e) {
          Log::error($e->getMessage());
      }
      
  6. Indentation Quirks:

    • Indentation configurator only works with Writer (not DOM or Reader).
  7. New: DOCTYPE Security Risk (v4.12.0):

    • DOCTYPE declarations can expose XML entities vulnerabilities (e.g., XXE attacks).
    • Always use disallow_doctype() in production environments:
      $writer->configure(disallow_doctype());
      
    • Legacy code without this configurator may be vulnerable. Audit existing XML generation.

Debugging Tips

  1. Inspect XMLWriter State: Use memory_output() to debug:

    $writer = Writer::inMemory()->configure(disallow_doctype());
    $writer->write($xmlStructure);
    $output = $writer->map(memory_output());
    dd($output); // Inspect raw XML (should lack DOCTYPE)
    
  2. Validate XML Against Schema:

    $validator = new Validator('schema.xsd');
    $errors = $validator->validate('data.xml', true); // Return errors instead of throwing
    dd($errors);
    
  3. Check for DOCTYPE Presence:

    use VeeWee\Xml\Reader\Reader;
    
    $reader = Reader::fromFile('data.xml');
    if ($reader->hasDoctype()) {
        throw new \RuntimeException('DOCTYPE detected! Use disallow_doctype() configurator.');
    }
    
  4. Performance with Large Files:

    • Prefer Reader over DOM for files >10MB.
    • Stream XML generation with Writer::forStream() and enforce security:
      $writer = Writer::forStream($stream)
                      ->configure(disallow_doctype());
      

Extension Points

  1. Custom Builders (Updated for Security): Extend the
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