XML-to-array, including the root key, ignoring empty elements and attributes, with significant 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]); Recursive
- 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;
- }
- }
Xml to array, not including root key
- function Xmltoarray ($xml)
- {
- $arr = Xml_to_array ($xml);
- $key = Array_keys ($arr);
- return $arr [$key [0]];
- }
An XPATH-like array selector
- 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 was not exists: '. $curpath);
- }
- Return $self ($result, $next);
- }
If the input array is a full numeric key, the element values are transferred sequentially to the $callback, otherwise they are transferred to $callback
- function Xml_array_each ($arr, $callback)
- {
- if (Func_num_args () <2) die (' Parameters error ');
- if (!is_array ($arr)) die (' parameter 1 shuld is an array! ');
- if (!is_callable ($callback)) die (' Parameter 2 shuld is 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;
- }
- ?>
Copy Code |