php XML轉換為數組的代碼

來源:互聯網
上載者:User
  1. // Xml 轉 數組, 包括根鍵,忽略空元素和屬性,尚有重大錯誤

  2. function xml_to_array( $xml )
  3. {
  4. $reg = "/<(\\w+)[^>]*?>([\\x00-\\xFF]*?)<\\/\\1>/";
  5. if(preg_match_all($reg, $xml, $matches))
  6. {
  7. $count = count($matches[0]);
  8. $arr = array();
  9. for($i = 0; $i < $count; $i++)
  10. {
  11. $key = $matches[1][$i];
  12. $val = xml_to_array( $matches[2][$i] ); // 遞迴
  13. if(array_key_exists($key, $arr))
  14. {
  15. if(is_array($arr[$key]))
  16. {
  17. if(!array_key_exists(0,$arr[$key]))
  18. {
  19. $arr[$key] = array($arr[$key]);
  20. }
  21. }else{
  22. $arr[$key] = array($arr[$key]);
  23. }
  24. $arr[$key][] = $val;
  25. }else{
  26. $arr[$key] = $val;
  27. }
  28. }
  29. return $arr;
  30. }else{
  31. return $xml;
  32. }
  33. }

  34. // Xml 轉 數組, 不包括根鍵

  35. function xmltoarray( $xml )
  36. {
  37. $arr = xml_to_array($xml);
  38. $key = array_keys($arr);
  39. return $arr[$key[0]];
  40. }

  41. // 類似 XPATH 的數組選取器

  42. function xml_array_select( $arr, $arrpath )
  43. {
  44. $arrpath = trim( $arrpath, '/' );
  45. if(!$arrpath) return $arr;
  46. $self = 'xml_array_select';
  47. $pos = strpos( $arrpath, '/' );
  48. $pos = $pos ? $pos : strlen($arrpath);
  49. $curpath = substr($arrpath, 0, $pos);
  50. $next = substr($arrpath, $pos);
  51. if(preg_match("/\\[(\\d+)\\]$/",$curpath,$predicate))
  52. {
  53. $curpath = substr($curpath, 0, strpos($curpath,"[{$predicate[1]}]"));
  54. $result = $arr[$curpath][$predicate[1]];
  55. }else $result = $arr[$curpath];
  56. if( is_array($arr) && !array_key_exists($curpath, $arr) )
  57. {
  58. die( 'key is not exists:' . $curpath );
  59. }
  60. return $self($result, $next);
  61. }

  62. // 如果輸入的數組是全數字鍵,則將元素值依次傳輸到 $callback, 否則將自身傳輸給$callback

  63. function xml_array_each( $arr, $callback )
  64. {
  65. if(func_num_args()<2) die('parameters error');
  66. if(!is_array($arr)) die('parameter 1 shuld be an array!');
  67. if(!is_callable($callback)) die('parameter 2 shuld be an function!');
  68. $keys = array_keys($arr);
  69. $isok = true;
  70. foreach( $keys as $key ) {if(!is_int($key)) {$isok = false; break;}}
  71. if($isok)
  72. foreach( $arr as $val ) $result[] = $callback($val);
  73. else
  74. $result[] = $callback( $arr );
  75. return $result;
  76. }
  77. ?>

複製代碼
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.