You can cast XML elements to PHP classes for better type safety and structure.
Model cast
Cast XML elements directly to Eloquent models:
use Flowgistics\XML\XML;class Note extends \Illuminate\Database\Eloquent\Model{ protected $fillable = [ 'to', 'from', 'heading', 'body', 'completed_at', ];}$xml = XML::import('notes.xml') ->cast('note')->to(Note::class) ->get();// $xml->note is now a Note model instance
Castable cast
Implement the Castable interface for custom casting logic:
use Flowgistics\XML\Casts\Castable;use Flowgistics\XML\XML;class TextNote implements Castable{ public function __construct($to, $from, $text) { // Your custom initialization logic } public static function fromCast(array $data): Castable { return new TextNote($data['to'], $data['from'], $data['body']); }}$xml = XML::import('notes.xml') ->cast('note')->to(TextNote::class) ->get();
Default cast
Cast to any PHP class with a constructor that accepts an array:
use Flowgistics\XML\XML;class MyNote{ public function __construct($data) { // Process the data array }}$xml = XML::import('notes.xml') ->cast('note')->to(MyNote::class) ->get();
Transformers allow you to modify XML data during import. You can use built-in transformers or create your own.
use Flowgistics\XML\XML;// Using the alias$xml = XML::import('notes.xml') ->expect('note')->as('array') ->get();// Or using the class directly$xml = XML::import('notes.xml') ->transform('note')->with(ArrayTransformer::class) ->get();// $xml->note will always be an array