PHP code example of magicsunday / xmlmapper

1. Go to this page and download the library: Download magicsunday/xmlmapper 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/ */

    

magicsunday / xmlmapper example snippets


namespace App\Model;

use MagicSunday\XmlSerializable;
use MagicSunday\XmlMapper\Annotation\XmlAttribute;

final class Author implements XmlSerializable
{
    public string $name = 'Jane Doe';
}

final class Book implements XmlSerializable
{
    #[XmlAttribute]
    public string $isbn = '978-3-16-148410-0';

    public string $title = 'The Title';

    public Author $author;

    /**
     * @var string[]
     */
    public array $tags = ['php', 'xml'];
}



use App\Model\Author;
use App\Model\Book;
use MagicSunday\XmlEncoder;
use MagicSunday\XmlMapper\Converter\CamelCasePropertyNameConverter;
use Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor;
use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
use Symfony\Component\PropertyInfo\PropertyInfoExtractor;

$extractor = new PropertyInfoExtractor(
    [new ReflectionExtractor()],
    // PhpDocExtractor resolves `@var` generics such as `Chapter[]`;
    // ReflectionExtractor covers native types, so an array property without a
    // docblock is still recognised as a collection, instead of being refused by
    // the default encoder or rendered by a lenient one as one empty element.
    [new PhpDocExtractor(), new ReflectionExtractor()]
);

$book         = new Book();
$book->author = new Author();

$encoder = new XmlEncoder($extractor, new CamelCasePropertyNameConverter());

echo $encoder->map($book);

/** @var string[] $tags */
/** @var Chapter[] $chapters */
/** @var array<int, Author|Chapter> $members */

$encoder->addType('bool', static fn (string $name, mixed $value): string => $value === true ? 'yes' : 'no');