spatie/array-to-xml
Simple PHP utility to convert arrays into XML strings. Supports custom root element names and configurable key handling (e.g., converting spaces to underscores). Ideal for quickly generating XML output from structured array data.
Start by installing the package via Composer: composer require spatie/array-to-xml. No Laravel service provider registration is needed—it’s a plain PHP utility. The core usage is straightforward:
use Spatie\ArrayToXml\ArrayToXml;
$xml = ArrayToXml::convert([
'user' => [
'@attributes' => ['id' => 123],
'name' => 'Jane Doe',
'email' => 'jane@example.com',
]
], 'response');
echo $xml; // Outputs valid XML with <response> root
The first example in the README covers the most common pattern—converting a simple nested array to XML—and is the best place to begin. For Laravel users, drop it into a controller method, job, or console command where XML generation is required (e.g., sitemap generation or legacy API responses).
return response($xml)
->header('Content-Type', 'application/xml');
ArrayToXml::convert([...], 'root', null, false) with echo inside a command.collect([...])->toArray() as input.@attributes, @value, and @cdata magic keys to embed metadata and unescaped content:
'product' => [
'@attributes' => ['sku' => 'ABC'],
'@cdata' => '<description>Raw <b>HTML</b></description>', // or use `@value` for plain text
]
ArrayToXml::convert($data, 'inventory', 'utf-8', false, '1.1');
@attributes, @value, or @cdata as regular array keys—they’re treated as special. If needed, escape them (e.g., product@attributes) or preprocess arrays.<items/>). If you need <items></items>, manually add a null or placeholder value.$pretty = true) in production—disabling it ($pretty = false) significantly speeds up generation.@namespace, @ns) are supported but poorly documented—refer to the unit tests for examples if needed.xmllint) in CI if schema compliance is critical.xml response helper is needed—just return the XML string with explicit application/xml header.How can I help you explore Laravel packages today?