PHP code example of mleczek / xml

1. Go to this page and download the library: Download mleczek/xml library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mleczek / xml example snippets


$dog = new Dog();
$converter = new XmlConverter($dog);
$outerXml = (string)$converter;
$outerXml = $converter->outerXml(); // equals __toString
$innerXml = $converter->innerXml();

use Mleczek\Xml\Xmlable;
use Mleczek\Xml\XmlConvertible;

class Dog
{
    use XmlConvertible;
    
    public $id = 5;
}

$dog = new Dog();
$xml = $dog->toXml(); // returns <result><id>5</id></result>
$xml = toXml($dog);   // without using XmlConvertible trait

$dog = new Dog();
$xml = $dog->toXmlAs('dog'); // returns <dog><id>5</id></dog>
$xml = toXmlAs($dog, 'dog'); // without using XmlConvertible trait

use Mleczek\Xml\Xmlable;

class Dog implements Xmlable
{
    public function xml()
    {
        // XML Body...
    }
}

$dog = new Dog();
$xml = $dog->toXml(['cat']); // returns <cat/>

public function xml()
{
    // <dog/>
    return ['dog'];
}

public function xml()
{
    // <dog><name>{$this->full_name}</name></dog>
    return [
        'dog' => [
            'name' => 'full_name'
        ]
    ];
}

public function xml()
{
    // <dog><hau/><hau2/><id>5</id></dog>
    return [
        'dog' => [
            'hau',          // self-closing element
            'hau2' => null, // self-closing element #2
            'id' => '=5',   // use "=" prefix for constant values
        ]
    ];
}

public function xml()
{
    $extra_elements = [];
    if($this->isSuperDog()) {
        $extra_elements = ['hau_power' => 5];
    }

    // $this->isSuperDog():
    // true: <dog><hau/><hau_power>5</hau_power></dog>
    // false: <dog><hau/></dog>
    return [
        'dog' => [
            'hau' => true,   // true -> self-closing element
            'miau' => false, // false -> skip element
            $extra_elements, // merge arrays
        ]
    ];
}

public function xml()
{
    // <dog name="{$this->full_name}" canHau id="5"/>
    return [
        'dog' => [
            '@name' => 'full_name' 
            '@canHau',            // without value
            '@id' => '=5',        // use "=" prefix for constant values
        ]
    ];
}

public function xml()
{
    // <dog canHau><id>5</id></dog>
    return [
        'dog' => [
            '@canHau',
            'id' => '=5'
        ]
    ];
}

use Mleczek\Xml\Xmlable;

class Dog implements Xmlable
{
    public function xml()
    {
        return '<dog/>';
    }
}