Apply transformations to XML data before processing
Transformers allow you to modify XML data during the import process. They’re perfect for filtering, normalizing, or reshaping data before it reaches your application.
The ArrayTransformer wraps elements in an array using Laravel’s Arr::wrap() helper. This ensures a consistent array format, even for single elements:
use Flowgistics\XML\XML;// Using the 'array' alias$xml = XML::import('notes.xml') ->expect('note')->as('array') ->get();// $xml->note will always be an array
This is particularly useful when XML might contain a single element or multiple elements:
<!-- Single note --><notes> <note>...</note></notes><!-- Multiple notes --><notes> <note>...</note> <note>...</note></notes>
Without the transformer, a single note would be an object, while multiple notes would be an array. The ArrayTransformer ensures consistent behavior.
Transformers run before casts, allowing you to prepare data before casting to classes:
$xml = XML::import('notes.xml') ->expect('note')->as('array') // Transform to array first ->cast('note')->to(Note::class) // Then cast to Note class ->get();
Keep transformers focused - Each transformer should do one thing well
Use type hints - Document expected input and output types
Handle edge cases - Check for null values and empty arrays
Make them reusable - Design transformers to work across different contexts
Test thoroughly - Ensure transformers handle all data variations
Transformers modify the data permanently. Once applied, the original data structure is replaced. If you need the original data, access it before applying transformers.