Menu Close
    Searching for an experienced Magento 2 Development Company ?

    Read XML Data from a XML file in Magento 2

    In Magento 2, there are a number of methods are available which are helpful to manage files and directory systems.
    In this blog, we are going to learn how we can read XML data from an XML file URL.

    In Magento 2, it provides \Magento\Framework\Filesystem\DriverInterface interface, where the fileGetContents method is declared, we use this method to read/get file content or data from any relative or absolute path or an URL. When we will read the XML file using an URL we can convert it into an Array by using the xmlToAssoc method of \Magento\Framework\Convert\Xml Class. We will use these steps in our Block file ReadXml.php inside app/code/Vendor/CustomModule/Block/Demo/ directory.

    We can also parse the XML data into an array by calling the xmlToArray method after loading the parser object(object of \Magento\Framework\Xml\Parser Class).

    Please follow the below steps to get the result:

    1. Create a Module.

    2. Create routename_controllername_action.xml file inside app/code/Vendor/CustomModule/view/frontend/layout/ directory.

    <?xml version="1.0"?>
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <referenceContainer name="content">
            <block class="Vendor\CustomModule\Block\Demo\ReadXml" 
                name="custom_demo_xml" 
                template="Vendor_CustomModule::readxml.phtml" 
                cacheable= "false"/>
        </referenceContainer>
    </page>

    3. Create Controller file ReadXml.php inside app/code/Vendor/CustomModule/Controller/Demo/ directory.

    <?php
    /**
     * Webkul Software.
     *
     * @category  Webkul
     * @package   Vendor_CustomModule
     * @author    Webkul
     * @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
     * @license   https://store.webkul.com/license.html
     */
    namespace Vendor\CustomModule\Controller\Demo;
    
    use Magento\Framework\App\Action\Action;
    use Magento\Framework\App\Action\Context;
    use Magento\Framework\View\Result\PageFactory;
    
    class ReadXml extends Action
    {
        /**
         * @var PageFactory
         */
        protected $_resultPageFactory;
    
        /**
         * initialization
         *
         * @param Context $context
         * @param PageFactory $resultPageFactory
         */
        public function __construct(
            Context $context,
            PageFactory $resultPageFactory
        ) {
            $this->_resultPageFactory = $resultPageFactory;
            parent::__construct($context);
        }
        
        /**
         * Execute ...
         */
        public function execute()
        {
            $resultPage = $this->_resultPageFactory->create();
            $resultPage->getConfig()->getTitle()->set(__("Read Xml"));
            return $resultPage;
        }
    }

    4. Create Block file ReadXml.php inside app/code/Vendor/CustomModule/Block/Demo/ directory.

    <?php
    /**
     * Webkul Software.
     *
     * @category  Webkul
     * @package   Vendor_CustomModule
     * @author    Webkul
     * @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
     * @license   https://store.webkul.com/license.html
     */
    namespace Vendor\CustomModule\Block\Demo;
    
    class ReadXml extends \Magento\Framework\View\Element\Template
    {
        /**
         * @var \Magento\Framework\Xml\Parser
         */
        private $parser;
    
        /**
         * @var \Magento\Framework\Xml\Parser
         */
        protected $convertXml;
    
        /**
         * @var \Magento\Framework\Filesystem\DriverInterface
         */
        protected $driver;
    
        public function __construct(
            \Magento\Framework\Xml\Parser $parser,
            \Magento\Framework\Convert\Xml $convertXml,
            \Magento\Framework\Filesystem\DriverInterface $driver,
            \Magento\Framework\View\Element\Template\Context $context
        ) {
            $this->parser     = $parser;
            $this->driver     = $driver;
            $this->convertXml = $convertXml;
            parent::__construct($context);
        }
    
        /**
         * Read xml data from URL and convert it into array by using xmlToAssoc method of \Magento\Framework\Convert\Xml Class
         * @return array
         */
        public function readXmlData()
        {
            $filePath = "http://example.com/products.xml";
            $fileContent = $this->driver->fileGetContents($filePath, null, null);
            $xml = new \SimpleXMLElement($fileContent);
            $xmlToArray = $this->convertXml->xmlToAssoc($xml);
            return $xmlToArray;
        }
    
        /**
         * Get parsed array from xml file's URL
         * @return array
         */
        public function readXmlDataByParser()
        {
            $filePath = "http://example.com/products.xml";
            $parsedArray = $this->parser->load($filePath)->xmlToArray();
            return $parsedArray;
        }
    }

    5. Create readxml.phtml file inside app/code/Vendor/CustomModule/view/frontend/templates/ directory.

    <?php
    $xmlData = $block->readXmlData();
    ?>
    <pre>
        <?php
        print_r($xmlData);
        $data = $block->readXmlDataByParser();
        print_r($data);
        ?>
    </pre>
    

    6. When we hit the ReadXml Controller in the browser’s window, we get the result like the following image when getting data from readXML data method from the Block file.

    ReadXmlControllerResponsePage

    7. When we hit the ReadXml Controller in the browser’s window, we get the result like the following image when getting data from readXmlDataByParser data method from the Block file.

    ReadXmlControllerResponseWhenUsingParser

    Hope this will be helpful. Thanks 🙂

    Previous Blog: Generate XML file in Magento 2

    . . .
    Discuss on Helpdesk

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top