Code for converting php xml to an array
// Xml to array, including the root key, ignore empty elements and attributes, there are still major errors
- Function xml_to_array ($ xml)
- {
- $ Reg = "/<(\ w +) [^>] *?> ([\ X00-\ xFF] *?) <\/\ 1> /";
- If (preg_match_all ($ reg, $ xml, $ matches ))
- {
- $ Count = count ($ matches [0]);
- $ Arr = array ();
- For ($ I = 0; $ I <$ count; $ I ++)
- {
- $ Key = $ matches [1] [$ I];
- $ Val = xml_to_array ($ matches [2] [$ I]); // recursion
- If (array_key_exists ($ key, $ arr ))
- {
- If (is_array ($ arr [$ key])
- {
- If (! Array_key_exists (0, $ arr [$ key])
- {
- $ Arr [$ key] = array ($ arr [$ key]);
- }
- } Else {
- $ Arr [$ key] = array ($ arr [$ key]);
- }
- $ Arr [$ key] [] = $ val;
- } Else {
- $ Arr [$ key] = $ val;
- }
- }
- Return $ arr;
- } Else {
- Return $ xml;
- }
- }
// Convert Xml to an array, excluding the root key
- Function xmltoarray ($ xml)
- {
- $ Arr = xml_to_array ($ xml );
- $ Key = array_keys ($ arr );
- Return $ arr [$ key [0];
- }
// Array selector similar to XPATH
- Function xml_array_select ($ arr, $ arrpath)
- {
- $ Arrpath = trim ($ arrpath ,'/');
- If (! $ Arrpath) return $ arr;
- $ Self = 'XML _ array_select ';
-
- $ Pos = strpos ($ arrpath ,'/');
- $ Pos = $ pos? $ Pos: strlen ($ arrpath );
- $ Curpath = substr ($ arrpath, 0, $ pos );
- $ Next = substr ($ arrpath, $ pos );
-
- If (preg_match ("/\ [(\ d +) \] $/", $ curpath, $ predicate ))
- {
- $ Curpath = substr ($ curpath, 0, strpos ($ curpath, "[{$ predicate [1]}]");
- $ Result = $ arr [$ curpath] [$ predicate [1];
- } Else $ result = $ arr [$ curpath];
-
- If (is_array ($ arr )&&! Array_key_exists ($ curpath, $ arr ))
- {
- Die ('Key is not exists: '. $ curpath );
- }
-
- Return $ self ($ result, $ next );
- }
// If the input array is a full-number key, the element values are transmitted to $ callback in sequence; otherwise, the elements are transmitted to $ callback.
- Function xml_array_each ($ arr, $ callback)
- {
- If (func_num_args () <2) die ('parameters error ');
- If (! Is_array ($ arr) die ('parameter 1 shcould be an array! ');
- If (! Is_callable ($ callback) die ('Parameter 2 shcould be an function! ');
- $ Keys = array_keys ($ arr );
- $ Isok = true;
- Foreach ($ keys as $ key) {if (! Is_int ($ key) {$ isok = false; break ;}}
- If ($ isok)
- Foreach ($ arr as $ val) $ result [] = $ callback ($ val );
- Else
- $ Result [] = $ callback ($ arr );
- Return $ result;
- }
- ?>
|