I decided to save setting in xml file since field takes only one value.

My XML file is like

<?xml version="1.0" encoding="UTF-8"?>
<setting>
    <setting1>setting1 value</setting1>
    <setting2>setting2 value</setting2> 
    <setting3>setting3 value</setting3> 
    ....
    ....
    ....
</setting>

Can anyone suggest me a simple php script to read, edit, add, and delete node and node values?

Comments

possible duplicate of Best XML Parser for PHP

Written by Gordon

@Gordon i was just expecting a hint where to begin with, since there are loads of stuff in manual

Written by experimentX

@Gordon and how to write in a xml file

Written by experimentX

Accepted Answer

If your XML is really that simple, you can use SimpleXML to CRUD it. SimpleXml will parse the XML into a tree structure of SimpleXmlElements. In a nutshell, you use it like this:

// CREATE
$config = new SimpleXmlElement('<settings/>');
$config->setting1 = 'setting1 value';         
$config->saveXML('config.xml');               

// READ
$config = new SimpleXmlElement('config.xml', 0, TRUE);
echo $config->setting1;
echo $config->asXml();

// UPDATE
$config->setting1 = 'new value';
$config->setting2 = 'setting2 value';
echo $config->asXml();

// DELETE
unset($config->setting1);
$config->setting2 = NULL;
echo $config->asXML();
unlink('config.xml');

Please refer to the PHP manual for further usage examples and the API description.

On a sidenote, if you really just have key/value pairs, you could also use a plain old PHP array to store them or a key/value store like DBA or even APC and memcached with a long ttl.

Written by Gordon
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki