Recent Posts

Showing posts with label XML. Show all posts
Showing posts with label XML. Show all posts

Generate dynamically a XML file from PHP

SimpleXML is the solution to generate the XML

<?php

$xml = new SimpleXMLElement('<xml/>');

for ($i = 1; $i <= 8; ++$i) {
    $track = $xml->addChild('track');
    $track->addChild('path', "song$i.mp3");
    $track->addChild('title', "Track $i - Track Title");
}

Header('Content-type: text/xml');
print($xml->asXML());

How to: CRUD in XML file from PHP

The XML file looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<setting>
    <setting1>setting1 value</setting1>
    <setting2>setting2 value</setting2> 
    <setting3>setting3 value</setting3> 
    ....
    ....
    ....
</setting>
How to add, edit, delete nodes and values with php?

Solution

If the 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.