4.7.x common.inc format_xml_elements($array)
5.x common.inc format_xml_elements($array)
6.x common.inc format_xml_elements($array)
7.x common.inc format_xml_elements($array)

Formats XML elements.

Parameters

$array: An array where each item represents an element and is either a:

  • (key => value) pair (<key>value</key>)
  • Associative array with fields:
    • 'key': element name
    • 'value': element contents
    • 'attributes': associative array of element attributes
    • 'encoded': TRUE if 'value' is already encoded

In both cases, 'value' can be a simple string, or it can be another array with the same format as $array itself for nesting.

If 'encoded' is TRUE it is up to the caller to ensure that 'value' is either entity-encoded or CDATA-escaped. Using this option is not recommended when working with untrusted user input, since failing to escape the data correctly has security implications.

Related topics

4 calls to format_xml_elements()
format_rss_channel in includes/common.inc
Formats an RSS channel.
format_rss_item in includes/common.inc
Formats a single RSS item.
NodeRSSContentTestCase::testNodeRSSContent in modules/node/node.test
Ensures that a new node includes the custom data when added to an RSS feed.
TaxonomyRSSTestCase::testTaxonomyRSS in modules/taxonomy/taxonomy.test
Tests that terms added to nodes are displayed in core RSS feed.

File

includes/common.inc, line 1789
Common functions that many Drupal modules will need to reference.

Code

function format_xml_elements($array) {
  $output = '';
  foreach ($array as $key => $value) {
    if (is_numeric($key)) {
      if ($value['key']) {
        $output .= ' <' . $value['key'];
        if (isset($value['attributes']) && is_array($value['attributes'])) {
          $output .= drupal_attributes($value['attributes']);
        }
        if (isset($value['value']) && $value['value'] != '') {
          $output .= '>' . (is_array($value['value']) ? format_xml_elements($value['value']) : (!empty($value['encoded']) ? $value['value'] : check_plain($value['value']))) . '</' . $value['key'] . ">\n";
        }
        else {
          $output .= " />\n";
        }
      }
    }
    else {
      $output .= ' <' . $key . '>' . (is_array($value) ? format_xml_elements($value) : check_plain($value)) . "</{$key}>\n";
    }
  }
  return $output;
}

Comments

peterx’s picture

This function does not handle CDATA. <![CDATA[]]> is converted to &lt;![CDATA[]]&gt;. You could change the < to {{lt}} then perform a string substitution afterwards.

Sibiraj PR’s picture

This function doesn't return header xml. How can i add <?xml version="1.0"?> to the xml structure?

laevensv@gmail.com’s picture

Why not like that : (concatenate)
$xmlstr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
$xmlstr .= format_xml_elements($xmlarray);

sillygwailo’s picture

This has been removed from Drupal 8 in favour of Twig templates. See the change record for more information.