PHP code example of robgridley / simple-xml-mapper

1. Go to this page and download the library: Download robgridley/simple-xml-mapper 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/ */

    

robgridley / simple-xml-mapper example snippets


use DateTime;
use SimpleXMLElement;
use SimpleXmlMapper\XmlMapper;
use Symfony\Component\PropertyInfo\PropertyInfoExtractor;
use Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor;
use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;

class Car
{
    /**
     * @var Manufacturer
     */
    public $manufacturer;

    /**
     * @var string
     */
    public $model;

    /**
     * @var int
     */
    public $year;

    /**
     * @var float
     */
    public $msrp;

    /**
     * @var array
     */
    public $colours = [];

    /**
     * @var Option[]
     */
    public $options = [];

    /**
     * @var bool
     */
    public $hybrid;

    /**
     * @var bool
     */
    public $awd;
}

class Manufacturer
{
    /**
     * @var string
     */
    public $name;

    /**
     * @var DateTime
     */
    public $founded;
}

class Option
{
    /**
     * @var string
     */
    public $name;
}

$listExtractors = [new ReflectionExtractor];
$typeExtractors = [new PhpDocExtractor];
$extractor = new PropertyInfoExtractor($listExtractors, $typeExtractors);

$mapper = new XmlMapper($extractor);
$mapper->addType(DateTime::class, function ($xml) {
    return DateTime::createFromFormat('Y-m-d H:i:s', $xml);
});

$xml = new SimpleXMLElement(file_get_contents('car.xml'));
$car = $mapper->map($xml, Car::class);