Read and Write XML Files In Magento

You can use Varien_Simplexml_Element class to read and write xml nodes. In magento the location of class file is lib/Varien/Simplexml/Element.php
Below is a sample of an XML file which I will read through Magento code. And after that i will also add an xml node into it.

<?xml version="1.0"?>
<config>
    <modules>
        <MyNamespace_MyModule>
            <version>0.1.0</version>        
        </MyNamespace_MyModule>
    </config>
 </modules> 


Here is the Magento/PHP code to read the XML data. I have kept the XML file in the root directory of Magento installation. The XML file is named test.xml. At first, the XML file is loaded and then it’s node are read with getNode function. Then, I have printed the result.
$xmlPath = Mage::getBaseDir().DS.'test.xml';
$xmlObj = new Varien_Simplexml_Config($xmlPath);
$xmlData = $xmlObj->getNode();
echo "<pre>"; print_r($xmlData); echo "</pre>";

You can add node with the setNode function. Here, I have set a node inside the node ‘modules’. The name of my new node is ‘employee’ and it’s value is ‘empid’.
$xmlPath = Mage::getBaseDir().DS.'test.xml';
$xmlObj = new Varien_Simplexml_Config($xmlPath); 
$xmlObj->setNode('modules/employee','empid'); 
$xmlData = $xmlObj->getNode()->asNiceXml();
 
// check if the XML file is writable and then save data
if(is_writable($xmlPath)) {
    @file_put_contents($xmlPath, $xmlData);
}

Comments

Popular Posts

Magmi Single and Multiple Category Importer