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);
}

3 comments:

  1. magento extension developmentwas very helpful in answering alot of questions.Thanks for posting.

    ReplyDelete
  2. thank you very much........this post help me to get module configuration as xml file very good.....I have find it few days...love you.....

    ReplyDelete
  3. The blog was absolutely fantastic! Lot of great information which can be helpful in some or the other way. Keep updating the blog, looking forward for more contents...Great job, keep it up..
    magento development company in bangalore 

    ReplyDelete