horat1us / php-xml-convertible
PHP Xml Convertible Object Trait
Installs: 1 841
Dependents: 0
Suggesters: 0
Security: 0
Stars: 1
Watchers: 3
Forks: 1
Open Issues: 0
Requires
- php: ^7.4 | ^8.0
- ext-dom: *
Requires (Dev)
- phpunit/phpunit: ^9.5
- squizlabs/php_codesniffer: ^3.10
This package is auto-updated.
Last update: 2024-12-05 15:14:53 UTC
README
This trait automatically converts your object to XML representation (DOMElement
).
All your public properties (you can override method getXmlProperties)
will be converted to attributes.
To declare children in your object you need to set $xmlChildren property.
To change element name you need to set $xmlElementName property
(short class name will be used by default)
Install
composer require horat1us/php-xml-convertible
Test
make test
Usage
You should just declare your class to implement Horat1us\XmlConvertibleInterface
and use Horat1us\\XmlConvertible
trait:
<?php namespace Horat1us\Examples; use Horat1us\XmlConvertible; use Horat1us\XmlConvertibleInterface; class Person implements XmlConvertibleInterface { use XmlConvertible; public $name; public $surname; public static function fromJson(string $json): Person { $array = json_decode($json, true); $object = new static; $object->name = $array['name'] ?? null; $object->surname = $array['surname'] ?? null; return $object; } }
About
This trait and interface can be useful when you create object than parse something and represents XML structure, like:
XmlConvertible::toXml Example 1
<?php require_once(dirname(__DIR__) . '/vendor/autoload.php'); use Horat1us\Examples\Person; $document = new \DOMDocument; $element = Person::fromJson('{"name": "Alexander", "surname": "Letnikow"}')->toXml($document); $document->appendChild($element); echo $document->saveXml();
Will output:
<?xml version="1.0"?> <Person name="Alexander" surname="Letnikow"/>
XmlConvertible::fromXml Example 2
<?php require_once(dirname(__DIR__) . '/vendor/autoload.php'); use Horat1us\Examples\Person; $xml = '<?xml version="1.0"?> <Person name="Alexander" surname="Letnikow"><Head size="big" mind="small" /></Person>'; $document = new \DOMDocument; $document->loadXML($xml); $person = Person::fromXml($document); echo print_r($person, true);
Will output:
Horat1us\Examples\Person Object
(
[name] => Alexander
[surname] => Letnikow
[xmlChildren] => Array
(
[0] => Horat1us\XmlConvertibleObject Object
(
[xmlChildren] => Array
(
)
[xmlElementName] => Head
[size] => big
[mind] => small
)
)
[xmlElementName] => Person
)
See tests to know more about all features.
License
This project is open-sourced software licensed under the MIT license