Category Archives: XML

SimpleXmlElement::Attributes()

Attributes() function return hash of attributes.
How to use review the code below.
[php]
try { $xml = self::_get_xml_obj( SETTINGS_FILE_NAME ); } catch ( Exception $e ) { throw $e; }
if( ! ( $xml->channel ) ) throw new Exception(‘No channel node extracted from xml’);

$attrs = $xml->channel[0]->attributes();
if( !isset( $attrs ) || count( $attrs) == 0 ) return false;

$settings_ar = array();
foreach ( $attrs as $key=>$value )
$settings_ar[$key] = (String) $value;

return $settings_ar;
[/php]

SimpleXmlElement – save indented tree

As everyone should be aware, SimpleXmlElement class is not capable to preserve the indents in xml output.
To achieve that the DOMDocument class comes in handy.
[php]
//Format XML to save indented tree rather than one line and save
$dom = new DOMDocument(’1.0′);
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($xml->asXML());
$dom->save(‘fileName.xml’);
[/php]