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.
Installation
composer require laminas/laminas-xml2json:^3.3.0
laminas/laminas-zendframework-bridge and zendframework/*, ensuring cleaner standalone usage.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"
}
}
}
Where to Look First
Xml2Json (check for method parameters like $options).tests/ for edge cases (e.g., namespaces, arrays).$options array for customization (e.g., keepArrayKey, attributesPrefix).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);
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"
}
}
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"]
}
}
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);
}
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) {}
Validator to ensure XML structure before conversion.
$validator = Validator::make(['xml' => $xml], ['xml' => 'required|xml']);
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);
}
SimpleXMLElement + json_encode) may be faster than this package, but test both.Namespace Handling
ns:item). Use namespaceSeparator to customize:
$options = ['namespaceSeparator' => '_'];
namespaceSeparator to '' to strip namespaces entirely.Attribute Key Collisions
<tag name="value">value</tag>), the attribute takes precedence under @attributes.attributesPrefix to avoid clashes:
$options = ['attributesPrefix' => 'attr_'];
Empty Elements
<empty/>) may not appear in output. Explicitly include them if needed:
$xml = '<root><empty/></root>';
$json = $converter->convert($xml, ['emptyTagHandling' => 'include']);
CDATA Sections
#cdata-section. No special handling required unless you need to strip it:
$options = ['cdataSectionHandling' => 'strip'];
Memory Limits
libxml_disable_entity_loader(true) if parsing external entities is unnecessary:
libxml_disable_entity_loader(true);
$json = $converter->convert($xml);
simplexml_load_string() to validate XML before conversion:
if (!simplexml_load_string($xml)) {
throw new \InvalidArgumentException("Invalid XML");
}
$options to ensure settings are applied:
$converter->convert($xml, ['debug' => true]); // (No built-in debug, but log $options)
spatie/xml-to-array.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);
}
}
Add Support for New XML Features
Extend the package to handle custom XML constructs (e.g., comments, processing instructions) by modifying the processNode() method.
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);
How can I help you explore Laravel packages today?