xttribute will make dealing with XML a breeze! DOMDocuments can now be cast to classes with PHP 8.1 attributes!
- PHP 8.1
Use composer to install
composer require xttribute/xttribute
Given the following XML
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
We can translate this easily to the following class with some attributes!
use Xttribute\Xttribute\Castable\Str;
class Note
{
public function __construct(
#[Str('/note/to')]
public readonly string $to,
#[Str('/note/from')]
public readonly string $from,
#[Str('/note/heading')]
public readonly string $heading,
#[Str('/note/body')]
public readonly string $body,
) {
}
}
Then we can run it through our DomDocumentCaster
and get our hydrated object!
use Xttribute\Xttribute\DOMDocumentCaster;
// $source to be populated, however you're receiving your XML
$xml = new DOMDocument();
$xml->loadXML($source);
$caster = new DOMDocumentCaster();
$caster->cast($doc, Note::class)
Other ways of using this package can be found in our examples.
Pull requests are welcome! For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.
composer test