PHP code example of sergeynezbritskiy / xml-io

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

    

sergeynezbritskiy / xml-io example snippets


$xmlString = ' xml string from above ';
$xmlReader = new \SergeyNezbritskiy\XmlIo\XmlReader();
$user = $xmlReader->stringToArray($xmlString, [
    //array element with key `id` will be created from attribute `id`
    'id' => '@id',
    //array element with key `name` will be created from tag `name`
    'name' => 'name',
    'born' => 'born',
    'born_format' => 'born.@format',
    'passport' => [
        'id' => '@id',
        'date' => 'date',
    ],
    //create simple list of items
    'keywords as keywords.keyword' => '{list}',
    //create element `addresses` which will be an array of associative arrays
    'addresses as addresses.address[]' => [
        'city' => 'city',
        'country' => 'country',
    ]
]);

the result will be smth like that:
$user = [
    'id' => '1',
    'name' => 'Sergey',
    'born' => '1988-20-12',
    'born_format' => 'ISO',
    'passport' => [
        'id' => 'MN123456',
        'date' => '2000-12-12',
    ],
    'keywords' => [
        'buono', 
        'brutto', 
        'cattivo'
    ],
    'addresses' => [
        [
            'city' => 'Kharkiv', 
            'country' => 'Ukraine'
        ],[
            'city' => 'London', 
            'country' => 'Great Britain'
        ],
    ]
];

and back, convert array to xml
$xmlWriter = new \SergeyNezbritskiy\XmlIo\XmlWriter();
$xml = $xmlWriter->toXmlString($user, 
'user' => [
    'attributes' => ['id'],
    'children' => [
        'name',
        'born',
        'passport' => [
            'attributes' => ['id'],
            'children' => 'date',
        ],
        'keywords' => [
            'children' => [
                'keyword[]' => [
                    'dataProvider' => 'keywords',
                    'text' => '{self}',
                ],
            ],
        ],
        'addresses' => [
            'children' => [
                'address[]' => [
                    'dataProvider' => 'addresses',
                    'children' => ['city', 'country'],
                ],
            ],
        ],
    ],
]);