Home » Magento, XML

Magento: Read Write XML

17 February 2010 551 views 2 Comments Popularity: 6% Share/Bookmark

I will be using Varien_Simplexml_Element class to read write xml nodes. The path to this class file is lib/Varien/Simplexml/Element.php

Here is a sample XML file which I am going to read through Magento code. I will also be adding an XML node to the following XML data.

<?xml version="1.0"?>
<config>
    <modules>
        <MyNamespace_MyModule>
            <version>0.1.0</version>
        </MyNamespace_MyModule>
    </modules>
    <frontend>
        <routers>
            <mymodule>
                <use>standard</use>
                <args>
                    <module>MyNamespace_MyModule</module>
                    <frontName>mymodule</frontName>
                </args>
            </mymodule>
        </routers>
        <layout>
            <updates>
                <mymodule>
                    <file>mymodule.xml</file>
                </mymodule>
            </updates>
        </layout>
    </frontend>
</config>

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 ‘mukesh’ and it’s value is ‘chapagain’.

$xmlPath = Mage::getBaseDir().DS.'test.xml';
$xmlObj = new Varien_Simplexml_Config($xmlPath);

$xmlObj->setNode('modules/mukesh','chapagain');

$xmlData = $xmlObj->getNode()->asNiceXml();

// check if the XML file is writable and then save data
if(is_writable($xmlPath)) {
	@file_put_contents($xmlPath, $xmlData);
}

Hope this helps. Thanks for reading.

From Mukesh Chapagain's Blog | Post Magento: Read Write XML

Related posts:

  1. Magento: Read config XML nodes
  2. PHP : Read Write Xml with DOMDocument
  3. PHP : Read Write Xml with SimpleXML
  4. Magento: Create, read, delete cookie
  5. Magento: Upgrading mysql setup of a module

2 Comments »

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.