PHP code example of fransverbeek / xml-transform

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

    

fransverbeek / xml-transform example snippets



// Optional add namespaces in the XML
$namespaces = ['oai' => 'http://www.openarchives.org/OAI/2.0/'];

// Define the mapping for the array that you want to have filled
$mapping = [
    'id' => [
        'xpath' => './/oai:identifier/text()'
    ],
    'material' => [
        'xpath' => './/oai:material/text()',
        'repeatable' => true // If elements are repeatable set this option so an array will be returned
    ],
];

$data = (new \XmlTransform\Mapper($mapping, '//oai:OAI-PMH/oai:ListRecords/oai:record', $namespaces))
    ->from('somefile.xml')
    ->transform();

// $data will contain something like
[
    ['id' => '12', 'material' => ['paint', 'pencil']],
    ['id' => '13', 'material' => ['pen', 'pencil']],
]

$data = (new \XmlTransform\Mapper($mapping, '//oai:OAI-PMH/oai:ListRecords/oai:record', $namespaces))
    ->from('somefile.xml')
    ->transformOne();

// $data will contain something like
['id' => '12', 'material' => ['paint', 'pencil']]


$mapping = [
    'id' => ['xpath' => './/oai:objectid/text()'],
    'creator' => [
        'repeatable' => true, // Mark the element as repeatable
        'context' => './/oai:constituent', // new context for the nested elements
        'values' => [
            'name' => ['xpath' => './/text()'],
            'death_date' => ['xpath' => './/@death_date'],
        ]
    ]
];

$transformer = new \XmlTransform\Mapper($mapping, '//oai:record', $namespaces);
$result = $transformer->from($xml)->transformOne();

// Result will contain something like this
[
    'id' => '3517',
    'creator' => [
        ['name' => 'Rembrandt', 'death_date' => '1669'],
        ['name' => 'Johannes Mock', 'death_date' => '1884'],
        ['name' => 'Georg Friedrich Schmidt', 'death_date' => '1775'],
    ]
]

$transformer->from($xml)->filter()->transform();

$mapping = [
    'record' => [
        'context' => './/data',
        'values' => [
            'title' => ['xpath' => './/title/text()'],
            'creator' => ['xpath' => './/creator/text()'], // optional
        ]
    ],
];

$transformer = new \XmlTransform\Mapper($mapping, '//record');
$result = $transformer->from($xml)->optionalElements()->filter()->transform();

// Result creator is missing.
[
    'record' => [
        'title' => 'test',
        'creator' => 'Bert',
    ],
],
[
    'record' => [
        'title' => 'test 2',
    ]
]