Magento – Magento 2 : How to i read Xml file data

data-migrationmagento2product-importxml

I have product file in XML format. I just need to read this file and import those data.

I have already use simplexml_load_file(file path) but it will work only small size of file. Is there any other way to read this large XML file ?

Best Answer

You can try this way :

 namespace Vendor\ModuleName\Model;  
      class ParseXmlClass 
         {
                /**
                 * @var \Magento\Framework\Module\Dir\Reader
                 */
                protected $moduleDirReader;

                /**
                 * @var \Magento\Framework\Xml\Parser
                 */
                private $parser;

                    ...

                public function getValue() 
                {
                    $filePath = $this->moduleDirReader->getModuleDir('etc', 'ModuleName') 
                       . '/yourxml.xml'
                    $parsedArray = $this->parser->load($filePath)->xmlToArray();
                    return $parsedArray['xmlNodeName'];
                }
         }
Related Topic