Array to XML Conversion in PHP using RSS_PHP

This how-to shows how to use RSS_PHP to convert an Array to XML using PHP

Array to XML

Using RSS_PHP we can convert any Array to XML in 2 or 3 lines depending how you look at it.

= array(
                        'associative' => array('a' => 'value a','b' => 'value b'),
                        'numerical' => array('value 1','value 2','value 3')

    $RSS_PHP = new rss_php;
    $RSS_PHP->loadArray($test_array'arraytest'); #the second param is an optional root node name.
echo $RSS_PHP->getXML();

RSS_PHP's approach to converting Arrays to XML

In the example above you'll notice that we have an associative array comprising of two arrays, the first being an associative array, the second being a numerical array.

Here's what the $test_array looks like in PHP.

    [associative] => Array
            [a] => value a
            [b] => value b

    [numerical] => Array
            [0] => value 1
            [1] => value 2
            [2] => value 3


Below you can find RSS_PHP's XML version of this Array.

<?xml version="1.0" encoding="UTF-8"?>
	<a>value a</a>
	<b>value b</b>
  <numerical>value 1</numerical>
  <numerical>value 2</numerical>
  <numerical>value 3</numerical>

Why do all the numerical array items have the same nodeName?
Think of an RSS document, with multiple <item>'s.. you can't replicate this in PHP as no two array items can have the same name, thus RSS_PHP assumes that all numerically indexed arrays hold multiple item's of the same type.

Valid XHTML 1.0 Strict

return to the top of the page