Weave 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

acfbentveld/xml

A Laravel/PHP package for working with XML. It offers a simple API to parse and read XML, convert XML into arrays or objects, and generate XML output, making common XML handling tasks cleaner and easier in Laravel applications.

View on GitHub
Deep Wiki
Context7

Getting Started

The package is a thin, fluent XML builder for Laravel — it does not replace DOMDocument or SimpleXML, it wraps them so you can assemble documents without string concatenation or manual DOM calls.

Start here:

  1. Install with Composer and rely on Laravel's package auto-discovery:

    composer require acfbentveld/xml
    

    If auto-discovery is disabled (older Laravel or dont-discover set), register ACFBentveld\XML\XMLServiceProvider manually in config/app.php and, if you use it, alias the facade.

  2. Read the builder class first. Open src/XMLBuilder.php (or the equivalent) in vendor/ — the public methods are what you'll actually use day-to-day. Skim the README for the root/nodes/attributes/save trio; the surface area is small, so 10 minutes of reading covers the whole API.

  3. First use case: stand up a "health" XML endpoint. Build a small document in a test or a php artisan tinker session and dump it to stdout before wiring it into a controller. This confirms the output shape (declaration, root, encoding, pretty-print) so you don't debug blind inside an HTTP response.

  4. Sanity-check output with SimpleXMLElement on the produced string — if it parses cleanly in SimpleXML, it will parse in any consumer.

A realistic first task: a controller that returns an RSS/sitemap/API feed. You build nodes from an Eloquent collection, return the resulting string from response()->make(...) with an application/xml header, and add a feature test that asserts on the parsed XML rather than on raw bytes.

Implementation Patterns

Fluent build-then-return in a controller — the natural shape:

public function feed()
{
    $xml = XMLBuilder::create('feed');          // root
    $xml->node('title', 'Latest posts');

    foreach (Post::latest()->take(20)->get() as $post) {
        $xml->node('entry')
              ->node('title', $post->title)
              ->node('link', route('posts.show', $post))
              ->end();
    }

    return response($xml->save(), 200, ['Content-Type' => 'application/xml']);
}

The key habit: always close the node you opened (->end() or the builder's equivalent) before moving to the next sibling. Treat it like writing well-balanced HTML.

Attributes on nodes — use them for IDs, types, and schema hints rather than encoding them as child elements:

$xml->node('entry', null, ['id' => $post->id]);

Save to disk instead of memory — for exports or anything destined for S3, call the save method with a path and skip keeping the string in scope:

$xml->save(storage_path('app/exports/posts.xml'));
Storage::disk('s3')->put('exports/posts.xml', $xml->save());

Extract a builder service. Don't grow a 200-line controller. Wrap construction in a dedicated class (PostFeedXml, InvoiceXml) with a single render(iterable $models): string method. This makes it testable, reusable from a queued job, and easy to cache. It also insulates the rest of your app from this specific package's API.

Compose with Eloquent resources/chunking. For large exports, stream or chunk the query and append to the builder, but watch memory (see gotchas). For anything above a few thousand rows, prefer chunked writes to a file over a single in-memory build.

Standard HTTP response. Laravel has no native XML response macro, so pair the builder with response()->make($xml->save(), 200, $headers). Set Content-Type: application/xml; charset=UTF-8 explicitly — browsers and many feed readers are stricter than JSON clients.

Testing pattern. Assert on structure, not whitespace:

$response = $this->get('/feed');
$response->assertOk();

$xml = simplexml_load_string($response->getContent());
$this->assertCount(20, $xml->entry);
$this->assertSame('Latest posts', (string) $xml->title);

This is the single most valuable habit with any builder package — the raw string is an implementation detail.

Gotchas and Tips

  • Adoption is near zero. Treat this as a convenience library you may need to fork. Don't put it on a critical path without a fallback; if the package is abandoned, you should be able to swap in a hand-rolled DOMDocument builder in an afternoon. That's another reason to isolate the builder behind your own render() interface.

  • In-memory DOM means in-memory cost. Most fluent XML builders assemble the whole tree before serializing. A 100k-row export will balloon PHP memory. Chunk, or stream node-by-node to a file handle instead of calling save() on a giant in-memory tree.

  • Escaping is handled, concatenation is not. The builder escapes &, <, >, quotes in text and attributes — which is exactly why you should never pass raw markup into a text node. If you need CDATA or unescaped HTML, check whether the builder exposes it; if not, that's a real limitation, not something to hack around with html_entity_decode.

  • Empty vs. self-closing nodes. Many builders collapse <tag></tag> to <tag/> or emit <tag/> for null. Some consumers (older SOAP clients, certain XSD validators) reject self-closing tags. Inspect the output and, if needed, coerce empty strings to a sentinel or adjust the builder.

  • Null and boolean coercion. true/false and null serialize inconsistently across builders — false may vanish entirely, null may become empty string or self-closing. Cast explicitly to '1'/'0' or 'true'/'false' at the call site rather than trusting the builder.

  • Namespaces are the usual weak spot. If you're targeting SOAP, RSS 2.0 with extensions, or Google sitemaps, verify xmlns and prefixed elements (xsi:type, atom:link) are supported natively. Prefixed attributes rarely work via a generic attribute() call. For namespace-heavy formats, DOMDocument with createElementNS is often the pragmatic choice.

  • Encoding. Force UTF-8 at the top of the document and ensure your DB connection is UTF-8. Mixed encoding shows up as mojibake in the XML declaration even when the payload looks fine.

  • Pretty-print is cosmetic. Don't write tests that match indentation — assertXmlStringEqualsXmlString-style comparison (or parsing with SimpleXML) is the only stable assertion.

  • Auto-discovery failures after composer update typically mean the package's extra.laravel.providers block is missing or Laravel's cache is stale. Run php artisan package:discover and then php artisan config:clear before assuming the package is broken.

  • Extension points to look for when you outgrow the defaults: a custom root name, custom XML declaration/encoding, and any way to inject a pre-built DOMDocument or SimpleXMLElement. If those aren't exposed, forking the builder is usually cheaper than fighting it — the class is small.

  • Debugging tip. When the output is malformed, dd($xml->save()) before returning the response. Nine times out of ten the bug is an unclosed node() call or a nested foreach that opened an element it never closed; the raw string makes that obvious in a way that a browser's "XML parsing error" screen does not.

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.
middlewares/firewall
qubiqx/montapacking
nyoncode/laravel-package-console
pnscripts/filament-broadquill-lite
pnscripts/laravel-sentfold-lite
vleap/mx-sdk-laravel-internal
twidpay/utils
htetmyathlaing/scout-elasticsearch-driver
artisan-toolbox/front-awesome
ls/client-assistant
users-au/laravel-client
robertmarney/lara-hierarchial-collections
simonschaufi/rule-doc-generator
emissaoja/emissaoja
blackbricksoftware/gravityforms-civicrm-form-processor
al-rahabi/fancy-crud
jinas/dhivatar-component
mltstephane/laravel-quality
bernskiold/laravel-talentlms
bernskioldmedia/laravel-form-architect