How to Convert Layout XML Content into Array in Magento 2

How to Convert Layout XML Content into Array in Magento 2

Hello Magento Friends,

In this tutorial, I will throw light on How to Convert Layout XML Content into Array in Magento 2. 

Sometimes we need to convert a specific layout.xml file into an array to perform some operations in Magento 2. Converting XML to an array in Magento 2 is helpful to get the layout file data and display it based on the requirement.

So let’s see How you can Convert the layout XML file into an array in Magento 2.

Steps to Convert Layout XML Content into Array in Magento 2:

Step 1: We are converting layout XML to array through root script that’s why we need to create root script at the below file path

magento_root_directory\pub\layouttojson.php

Now, add the code as follows

<?php 
use Magento\Framework\App\Bootstrap;

require  __DIR__ .'/../app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$utilityFiles = $objectManager->get('Magento\Framework\App\Utility\Files');

$fileList = $utilityFiles->getLayoutFiles(['area_name' => 'frontend'], false);
foreach ($fileList as $configFile)
{
    if (strpos($configFile, 'layout_file_name.xml') !== false)
    {
	$configXml = simplexml_load_file($configFile);
	print_r($configXml);
    }
}

Conclusion:

With the help of the above steps, you can effortlessly convert Layout XML Content into Array in Magento 2. You can also Convert CURL XML Response into an Array in Magento 2.

If you have any doubt let me know through the comment section. Share the tutorial with your friends and stay in touch with us!

Happy Coding!

Previous Article

Magento 2: How to Add Storeview Switcher in Custom Admin Grid using UI Component

Next Article

Method to Apply Coupon Code Automatically in Magento 2

Write a Comment

Leave a Comment

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

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨