I have read a fair few tutorials written by others using classes and DOM functions to create XML from arrays. But what happens if you have an older PHP installation or prefer to keep things really simple as I do.
The following function declarations generate an XML string from an associative array. In my scripts that use it, it’s usually coupled with a download function so that XML is generated on the fly and then downloaded to a file. The main advantage of this is that you can write a basic import script using the SimpleXML library to restore the array at any time which makes it perfect for use as part of a backup/restore system.
Wordpress stores alot of it’s sitewide data in a table called wp_options which stores a named key and a value string for each piece of information. Plugins can also use this table by using the add_option, update_option, delete_option and get_option functions passing values, arrays or objects along with a key name. This isn’t an ideal data structure but does mean that plugin writers can easily store information without bloating the database with unnecessary and often badly designed tables.
The Code..
function generate_xml_from_array($array, $node_name) {
$xml = '';
if (is_array($array) || is_object($array)) {
foreach ($array as $key=>$value) {
if (is_numeric($key)) {
$key = $node_name;
}
$xml .= '<' . $key . '>' . "\n" . generate_xml_from_array($value, $node_name) . '</' . $key . '>' . "\n";
}
} else {
$xml = htmlspecialchars($array, ENT_QUOTES) . "\n";
}
return $xml;
}
function generate_valid_xml_from_array($array, $node_block='nodes', $node_name='node') {
$xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
$xml .= '<' . $node_block . '>' . "\n";
$xml .= generate_xml_from_array($array, $node_name);
$xml .= '</' . $node_block . '>' . "\n";
return $xml;
}
Usage
You can use the above functions by generating an array or object as normal and then using the following code. The function returns the XML and you can then do with it as you wish.
$xml = generate_valid_xml_from_array($array);
Things to consider
XML doesn’t allow for numeric tags so any numbers are replaced by the content of the $node_name variable. XML also doesn’t allow for certain special characters within it’s tags and ,for this reason, the htmlspecialchars function is passed over the raw data before it is placed into the string.
You can, however make use of cdata tags which tells XML readers to essentially ‘ignore whats coming next’. See the w3schools explanation of cdata here: http://www.w3schools.com/XML/xml_cdata.asp. There is no right or wrong way to escape data but if you have problems with my script then factor in the cdata tags replacing the htmlspecialchars call and see how you get on.
Alternatively feel free to contact me by commenting on this post or using the contact form and I will work with you to get your script working.