Magento 2 create custom xml config reader php class

If you want to introduce custom xml config file in Magento 2 then you will need to create custom php classes for reading xml file and converting to array. Let start with our working example.

For start we need to create xml file. In our case we created file in our test module on location: __magento_root__/app/code/Potkoc/Api/etc/potkoc.xml . You can see content of our file below:

Also we need to create xsd file on location:  __magento_root__/app/code/Potkoc/Api/etc/potkoc.xsd.
For generating xsd I used online tool

Next step is creating php classes.

The main class is Potkoc\Api\Model\Config\Reader

Just note: $_idAttributes is array which contains fully qualified XPaths. It’s very important for merging more xml files to one. Try to experiment with this values and you will see result.

You can see that we defined xml filename potkoc.xml. Also we defined our custom type in di.xml and set arguments, filename, converter and schemaLocator class.

Next step is defining \Potkoc\Api\Model\Config\SchemaLocator class:

And last thing is creating  Potkoc\Api\Model\Config\Converter class. In this class you should to code your custom logic for converting xml data to array.

If you use our classes for reading xml then you will get next result:

You will get next output:

I hope that you understand logic 😉

You may also like...

Leave a Reply