Back to Top

Generate XML file in Magento 2

Updated 24 July 2024

In this blog, we are going to learn that how we can generate XML files or how we can write data in xml file.

In Magento 2, it provides \Magento\Framework\Convert\ConvertArray class that contains the assocToXml method to convert an array into XML format. This formatted data we can write in the XML file.

In the following example, we have created an array that will be written in the XML file

Here, we have created GenerateXml.php Controller file 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;

class GenerateXml extends Action
{
    /**
     * @var \Magento\Framework\Filesystem\Io\File
     */
    protected $file;

    /**
     * @var \Magento\Framework\Convert\ConvertArray
     */
    protected $convertArray;
    
    /**
     * @var \Magento\Framework\Controller\Result\JsonFactory
     */
    protected $resultJsonFactory;

    /**
     * initialization
     *
     * @param Context $context
     * @param \Magento\Framework\Filesystem\Io\File $file
     * @param \Magento\Framework\Convert\ConvertArray $convertArray
     * @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
     */
    public function __construct(
        Context $context,
        \Magento\Framework\Filesystem\Io\File $file,
        \Magento\Framework\Convert\ConvertArray $convertArray,
        \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
    ) {
        $this->file         = $file;
        $this->convertArray = $convertArray;
        $this->resultJsonFactory = $resultJsonFactory;
        parent::__construct($context);
    }

    /**
     * Execute
     * @return json
     */
    public function execute()
    {
        $result = $this->resultJsonFactory->create();
        $flag   = $this->generateXml(); //call method to generate xml file
        $data   = ['message' => '', 'success' => false];
        if ($flag) {
            $data   = ['message' => 'File products.xml created.', 'success' => true];
        } else {
            $data   = ['message' => 'Something went wrong.', 'success' => false];
        }
        return $result->setData($data);
    }

    /**
     * Generate xml file
     * @return bool
     */
    public function generateXml()
    {
        $result = false;
        try {
            $product1 = [
                "productId" => 1,
                "productName" => "T-Shirt",
                "sku" => "tshirt",
                "price" => 45,
                "baseCurrency" => "USD",
                "customAttributes" => [
                    "color" => "Red",
                    "printType" => "Floral",
                    "sellerInfo" => [
                        "sellerName" => "Saroz",
                        "contact" => 987678
                    ]
                ]
            ];
            $product2 = [
                "productId" => 2,
                "productName" => "Women T-Shirt",
                "sku" => "w-tshirt",
                "price" => 55,
                "baseCurrency" => "EUR",
                "customAttributes" => [
                    "color" => "Green",
                    "printType" => "Plain",
                    "sellerInfo" => [
                        "sellerName" => "Reema",
                        "contact" => 898912
                    ]
                ]
            ];
            $products = [
               "productList1" => [
                  "product1"=>$product1,
                  "product2"=>$product2
               ]
            ];
            
            // ConvertArray function assocToXml to create xmlContents
            $xmlContents = $this->convertArray->assocToXml($products, "productLists");
    
            // convert it to xml using asXML() function
            $content = $xmlContents->asXML();
            
            $this->file->write("products.xml", $content);
            $result = true;
        } catch(\Exception $e) {
            $result = false;
        }
        return $result;
    }
}

When we execute the above controller in the browser’s window, we get the following response, and an XML file generate named as products.xml inside <magento-root-dir>/pub/ directory.

Searching for an experienced
Magento 2 Company ?
Find out More
generatexmlControllerResponse
GenerateXml Controller’s Response
productsDotXmlFileResponse
array data in XML format in products.xml file

Note: Don’t pass any value in a simple array format like [“XL”, “XS”] in any key. It should be like [“size1″=>”XL”, “size2″=>”XS”] associative array. Because when you will use simple array like [“XL”, “XS”] format, then generated XML will not be valid.

Please refer to the following example for a better understanding.

Example: Array $product contains a simple array in the “size” key. Its generated XML will be in the following XML format. But when you will open this XML in the browser’s window, it will show an error like the following image.

$products = [
                "productId" => 1,
                "productName" => "T-Shirt",
                "sku" => "tshirt",
                "price" => 45,
                "baseCurrency" => "USD",
                "customAttributes" => [
                    "color" => "Red",
                    "size" => ["XL", "XS"]
                ]
            ];
            // ConvertArray function assocToXml to create xmlContents
            $xmlContents = $this->convertArray->assocToXml($products, "productLists");
    
            // convert it to xml using asXML() function
            $content = $xmlContents->asXML();
            
            $this->file->write("products.xml", $content);
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<productLists>
    <productId>1</productId>
    <productName>T-Shirt</productName>
    <sku>tshirt</sku>
    <price>45</price>
    <baseCurrency>USD</baseCurrency>
    <customAttributes>
        <color>Red</color>
        <size>
            <0>XL</0>
            <1>XS</1>
        </size>
    </customAttributes>
</productLists>
incorrectXmlFormat
Error when the key name is integer type like 0, 1, etc.

Hope this will be helpful. Thanks 🙂

Next Blog: Read XML Data from a XML file in Magento 2

. . .

Leave a Comment

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


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home