horat1us/php-xml-convertible

PHP Xml Convertible Object Trait

1.4.0 2018-03-22 11:22 UTC

This package is auto-updated.

Last update: 2024-03-29 03:31:57 UTC


README

Build Status Code Coverage Scrutinizer Code Quality Latest Stable Version Latest Unstable Version License Total Downloads

  1. Trait
  2. Interface
  3. Examples

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