xml解析 微信消息

php

2014-07-03 13:07

<?php

$string="<xml>

<ToUserName><![CDATA[toUser]]></ToUserName>

<FromUserName><![CDATA[FromUser]]></FromUserName>

<CreateTime>123456789</CreateTime>

<MsgType><![CDATA[event]]></MsgType>

<Event><![CDATA[subscribe]]></Event>

</xml>";


$dom = new DOMDocument();

$dom->loadXML($string);

$a=getArray($dom->documentElement);

print_r($a);



function getArray($node) {

  $array = false;


/*  if ($node->hasAttributes()) {

    foreach ($node->attributes as $attr) {

      $array[$attr->nodeName] = $attr->nodeValue;

    }

  }*/


  if ($node->hasChildNodes()) {

    if ($node->childNodes->length == 1) {

      $array[$node->firstChild->nodeName] = $node->firstChild->nodeValue;

    } else {

      foreach ($node->childNodes as $childNode) {

      if ($childNode->nodeType != XML_TEXT_NODE) {

        $array[$childNode->nodeName]=$childNode->nodeValue;

      }

    }

  }

  } else {

    return $node->nodeValue;

  }

  return $array;

}

?>