Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A simple program to CRUD node and node values of xml file [closed]

Tags:

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?

like image 946
Santosh Linkha Avatar asked Feb 05 '11 09:02

Santosh Linkha


2 Answers

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');
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.

like image 107
Gordon Avatar answered Sep 23 '22 08:09

Gordon


You can use the PHP XQuery extension to do the job:

let $data := <setting>
    <setting1>setting1 value</setting1>
    <setting2>setting2 value</setting2> 
    <setting3>setting3 value</setting3> 
</setting>
return {
    (: Update :)
    replace value of node $data/setting1/text() with "Hello World";
    (: Delete :)
    delete node $data/setting2;
    (: Read :)
    $data
}

You can try the example above live at http://www.zorba-xquery.com/html/demo#BJ2a2bNxJc8JVZAl0qyjAelwN9s=

Instructions on how to install the XQuery PHP extension are available at http://www.zorba-xquery.com/html/entry/2011/12/27/PHP_Meets_XQuery

like image 20
wcandillon Avatar answered Sep 21 '22 08:09

wcandillon