You are here

function xml2array in Campaign Monitor 5.2

Converts an XML document to an array. Note that this only recognizes element names (which become keys) and text data (which become values)--attributes are not saved. Note also that if two or more elements exist at the same depth, the value for that key becomes a list of values. For example,

<code><xml><item>1</item></xml>"</code> is equivalent to

<code>array( 'xml' => array( 'item' => '1' ) )</code>

However,

<code><xml><item>1</item><item>2</item></xml></code>

is equivalent to

<code>array( 'xml' => array( 'item' => array( '1', '2' ) ) )</code>

Lastly, a node must either contain other nodes or non-empty text, not both. So

<code><xml><item> hii there<subitem>1</subitem></item></xml></code>

is incorrect, but

<code><xml><item><subitem>1</subitem><text>hii there</text></item></xml></code>

is correct. This won't crash the code, but it won't be put in to the array as you'd expect (and the inverse function array2xml() won't return the XML you'd expect).

Parameters

string $str The XML body.:

string $root (Optional) The start path within the XML body.:

string $charset (Optional) The character set of the XML document.:

Return value

array The converted XML document.

1 call to xml2array()
CMBase::makeCall in lib/CMBase.php
* The direct way to make an API call. This allows developers to include new API * methods that might not yet have a wrapper method as part of the package. * *

File

lib/CMBase.php, line 778

Code

function xml2array($str, $root = '/', $charset = 'utf-8') {
  $xmlp = xml_parser_create($charset);
  $xmlarr = new XMLArrayInstance($root);
  xml_parser_set_option($xmlp, XML_OPTION_CASE_FOLDING, false);
  xml_set_element_handler($xmlp, array(
    &$xmlarr,
    'start',
  ), array(
    &$xmlarr,
    'end',
  ));
  xml_set_character_data_handler($xmlp, array(
    &$xmlarr,
    'data',
  ));

  //xml_set_default_handler( $xmlp, array( $xmlarr, 'ddefault' ) );
  $cur = 0;
  $len = strlen($str);
  $c_sz = 2048;
  while ($cur < $len) {
    $chunk = substr($str, $cur, $c_sz);
    $cur += $c_sz;
    if (!xml_parse($xmlp, $chunk, !($cur < $len))) {
      echo "xml2array() error: Line ", xml_get_current_line_number($xmlp), ': ', xml_error_string($xmlp);
      break;
    }
  }
  return $xmlarr->array;
}