Warning: curl_exec() has been disabled for security reasons in /pub/host/sunboyu/sunboyu/www/wp-includes/http.php on line 1022
xml与array互转函数 » Blog Archive 一个程序猿 孙小一,孙小二,PHP,MYSQL,LINUX,APACHE,原创技术,扯淡

xml与array互转函数

作者 : admin 于 2009-05-31 18:42:11 标签: ,
2009
05-31

突然发现写程序不像原来思路那么清晰了,一个递归居然想了半天,不过还是凑合着写了一个简单的xml与array互转的函数,来实现跟其他系统的对接。

原来一直用的是拼凑的方式生成xml,这次使用了DOMDocument对象。不知道这个类是否有非法字符的问题,待测试一下便知。

  1. class AXML
  2. {
  3. var $dom = '';
  4. #    array to xml       ###########################################
  5.     #array to xml
  6. function array2xml( $array )
  7. {
  8. $this->dom = new DOMDocument('1.0', 'utf-8');
  9. $this->dom->formatOutput = true;
  10. $this->_array( array( 'root' => $array ) , $this->dom );
  11. echo $this->dom->saveXML();
  12. }
  13.  
  14. #array to dom
  15. function _array( $array = array() , $dom )
  16. {
  17. $i = 0;
  18. foreach( $array as $key => $value )
  19. {
  20. if( is_array( $value ) )
  21. {
  22. //遍历
  23. $node[$i] = $this->dom->createElement( $key );
  24. $dom->appendChild( $node[$i] );
  25. $this->_array( $value , $node[$i] );
  26. }
  27. else
  28. {
  29. $node[$i] = $this->dom->createElement( $key , $value );
  30. $dom->appendChild( $node[$i] );
  31. }
  32. $i++;
  33. }
  34. }
  35. #   xml  to array       ###########################################
  36. #xml to array
  37. function xml2array( $xmls )
  38. {
  39. $array = array();
  40. $this->dom = new SimpleXMLElement( $xmls );
  41. print_r( $this->_object( $this->dom ) );
  42. }
  43. #object to array
  44. function _object( $object )
  45. {
  46. $array = array();
  47. $t = get_object_vars( $object );
  48. $i = 0;
  49. foreach( $t as $key => $value )
  50. {
  51. if(is_object($value))
  52. {
  53. $array[$key] = $this->_object( $value );
  54. }
  55. else
  56. {
  57. $array[$key] = $value;
  58. }
  59. $i++;
  60. }
  61. return $array;
  62. }
  63. }
  64. $xml = new AXML();
  65. $xml->array2xml( $array );
  66. $xml->xml2array( $xml_string );

评论 2

  1. 废墟 Says:

    xmlrpc….

  2. admin Says:

    我做的是个php与python之间的xmlrpc,只不过自己实现比较有意思。

发表评论




XHTML:你可以使用的标签: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

(若看不到验证码,请重新加载页面。)