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 Xml2Json Laravel Package

laminas/laminas-xml2json

Convert XML to JSON in PHP via Laminas, with options for simple/pretty output and flexible handling of attributes, elements, and namespaces. Useful for bridging XML-based APIs and JSON consumers.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require laminas/laminas-xml2json:^3.3.0
    
    • No additional configuration is required for basic usage. This release drops compatibility with laminas/laminas-zendframework-bridge and zendframework/*, ensuring cleaner standalone usage.
  2. First Use Case: Basic XML-to-JSON Conversion

    use Laminas\Xml2Json\Xml2Json;
    
    $xmlString = '<root><item id="1">Test</item></root>';
    $converter = new Xml2Json();
    $json = $converter->convert($xmlString);
    
    echo $json;
    

    Output:

    {
      "root": {
        "item": {
          "@attributes": {
            "id": "1"
          },
          "#text": "Test"
        }
      }
    }
    
  3. Where to Look First

    • Class Docs: Xml2Json (check for method parameters like $options).
    • Tests: tests/ for edge cases (e.g., namespaces, arrays).
    • Options: Review $options array for customization (e.g., keepArrayKey, attributesPrefix).
    • Release Notes: 3.3.0 highlights the removal of Zend Framework bridge dependencies, ensuring standalone compatibility.

Implementation Patterns

Core Workflows

  1. Standard Conversion with Attributes

    $options = [
        'attributesPrefix' => 'attr_', // Prefix attributes (e.g., `attr_id` instead of `@attributes.id`)
        'keepArrayKey' => true,        // Preserve array keys for repeated elements
    ];
    $json = $converter->convert($xml, $options);
    
  2. Handling Namespaces

    $xmlWithNs = '<ns:root xmlns:ns="urn:test"><ns:item>Data</ns:item></ns:root>';
    $json = $converter->convert($xmlWithNs, ['namespaceSeparator' => '']);
    

    Output:

    {
      "root": {
        "item": "Data"
      }
    }
    
  3. Array Conversion for Repeated Elements

    $xmlArray = '<root><item>1</item><item>2</item></root>';
    $json = $converter->convert($xmlArray, ['keepArrayKey' => true]);
    

    Output:

    {
      "root": {
        "item": ["1", "2"]
      }
    }
    
  4. Integration with Laravel Requests

    use Illuminate\Http\Request;
    
    public function parseXmlRequest(Request $request) {
        $xml = $request->getContent();
        $converter = new Xml2Json();
        $data = json_decode($converter->convert($xml), true);
        return response()->json($data);
    }
    
  5. Service Provider Binding (Laravel)

    // app/Providers/AppServiceProvider.php
    public function register() {
        $this->app->singleton(Xml2Json::class, function () {
            return new Xml2Json(['attributesPrefix' => 'attr_']);
        });
    }
    

    Usage in Controllers:

    use Xml2Json;
    
    public function __construct(private Xml2Json $converter) {}
    

Integration Tips

  • Validation: Combine with Laravel’s Validator to ensure XML structure before conversion.
    $validator = Validator::make(['xml' => $xml], ['xml' => 'required|xml']);
    
  • Error Handling: Wrap conversion in a try-catch for malformed XML:
    try {
        $json = $converter->convert($xml);
    } catch (\Exception $e) {
        Log::error("XML conversion failed: " . $e->getMessage());
        return response()->json(['error' => 'Invalid XML'], 400);
    }
    
  • Performance: For large XML files, stream processing (e.g., SimpleXMLElement + json_encode) may be faster than this package, but test both.
  • Standalone Compatibility: This release removes Zend Framework dependencies, making it ideal for pure Laravel projects without legacy concerns.

Gotchas and Tips

Pitfalls

  1. Namespace Handling

    • Default behavior includes namespaces in keys (e.g., ns:item). Use namespaceSeparator to customize:
      $options = ['namespaceSeparator' => '_'];
      
    • Fix: Set namespaceSeparator to '' to strip namespaces entirely.
  2. Attribute Key Collisions

    • If XML has both an attribute and child with the same name (e.g., <tag name="value">value</tag>), the attribute takes precedence under @attributes.
    • Workaround: Use attributesPrefix to avoid clashes:
      $options = ['attributesPrefix' => 'attr_'];
      
  3. Empty Elements

    • Empty tags (e.g., <empty/>) may not appear in output. Explicitly include them if needed:
      $xml = '<root><empty/></root>';
      $json = $converter->convert($xml, ['emptyTagHandling' => 'include']);
      
  4. CDATA Sections

    • CDATA content is converted to #cdata-section. No special handling required unless you need to strip it:
      $options = ['cdataSectionHandling' => 'strip'];
      
  5. Memory Limits

    • Large XML files may hit PHP’s memory limit. Use libxml_disable_entity_loader(true) if parsing external entities is unnecessary:
      libxml_disable_entity_loader(true);
      $json = $converter->convert($xml);
      

Debugging Tips

  • Verify Input XML: Use simplexml_load_string() to validate XML before conversion:
    if (!simplexml_load_string($xml)) {
        throw new \InvalidArgumentException("Invalid XML");
    }
    
  • Inspect Options: Dump $options to ensure settings are applied:
    $converter->convert($xml, ['debug' => true]); // (No built-in debug, but log $options)
    
  • Check for Deprecations: The package is unmaintained (last release 2024, but now standalone). Monitor for forks or alternatives like spatie/xml-to-array.

Extension Points

  1. Custom Output Formatting Override the convert() method or extend the class to modify JSON structure:

    class CustomXml2Json extends Xml2Json {
        protected function processNode($node) {
            // Custom logic here
            return parent::processNode($node);
        }
    }
    
  2. Add Support for New XML Features Extend the package to handle custom XML constructs (e.g., comments, processing instructions) by modifying the processNode() method.

  3. Laravel Macro Add a macro to the Xml2Json class for reusable configurations:

    Xml2Json::macro('withLaravelOptions', function () {
        return new static([
            'attributesPrefix' => 'laravel_',
            'keepArrayKey' => true,
        ]);
    });
    

    Usage:

    $json = app(Xml2Json::class)->withLaravelOptions()->convert($xml);
    
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