2008년 1월 22일 화요일

DOM TO ARRAY SAMPLE

<?php

function dom_to_simple_array($domnode, &$array) {
  $array_ptr = &$array;
  $domnode = $domnode->firstChild;
  while (!is_null($domnode)) {
    if (! (trim($domnode->nodeValue) == "") ) {
      switch ($domnode->nodeType) {
        case XML_TEXT_NODE: {
          $array_ptr['cdata'] = $domnode->nodeValue;
          break;
        }
        case XML_ELEMENT_NODE: {
          $array_ptr = &$array[$domnode->nodeName][];
          if ($domnode->hasAttributes() ) {
            $attributes = $domnode->attributes;
            if (!is_array ($attributes)) {
              break;
            }
            foreach ($attributes as $index => $domobj) {
              $array_ptr[$index] = $array_ptr[$domobj->name] = $domobj->value;
            }
          }
          break;
        }
      }
      if ( $domnode->hasChildNodes() ) {
        dom_to_simple_array($domnode, $array_ptr);
      }
    }
    $domnode = $domnode->nextSibling;
  }
}

  # now, let's make a sample string containing some XML
  $strXMLData = "<contacts>
       <contact>
         <name>
           John Doe
         </name>
         <phone>
           123-456-7890
         </phone>
       </contact>
       <contact>
         <name>
           Mary Smiley
         </name>
         <phone>
           567-890-1234
         </phone>
       </contact>
     </contacts>";

  # create a DOM tree xml object (hierarchical array) from
  # this XML string
  $domdoc = new DOMDocument;
  $domdoc->loadXML($strXMLData);

  # now simplify the DOM array into a very simple array structure

  # first, create an empty array to be filled with your
  # simplified array result..
  $aData = array();

  # now, pass the dom document and your empty array to the
  # converter function.
  dom_to_simple_array($domdoc, $aData);

  # now $aData contains your simplified array, so print it out
?><html>
<body>
<p>there are <? echo count($aData['contacts'][0]['contact']); ?>
contacts</p>
<p>the 2nd contact's phone number is
<?echo $aData['contacts'][0]['contact'][1]['phone'][0]['cdata']; ?>
</p>
<hr />
<p>Here is the raw array structure:</p>
<pre>
<? print_r($aData); ?>
</pre>
</body>
</html>

댓글 없음:

댓글 쓰기