note 96948 deleted from function.xml-parse by danbrown
| From: | danbrown@php.net | Date: | Wed, 24 Mar 2010 15:58:37 +0000 |
| Subject: | note 96948 deleted from function.xml-parse by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-167356@lists.php.net to get a copy of this message | ||
Note Submitter: ben_isat_chemica__co_uk
----
@vladimir_wof_nikolaich_dot_ru
I wanted to return multiple nodes with the same name at the same level:
<root>
<container>
<node>a</node>
<node>b</node>
<node>c</node>
<node>d</node>
</container>
</root>
I came up with this function as a small modification to yours. I suggest use of both for different
purposes and make no claims as to the quality of the algorithm:
//
// use this to get nodes of tree by path with '/' terminator
//
function get_values_by_path($__xml_tree, $__tag_path)
{
$tmp_arr =& $__xml_tree;
$results = array();
$tag_path = explode('/', $__tag_path);
for ($i=0; $i < count($tag_path); $i++)
{
$tag_name = $tag_path[$i];
$res = false;
foreach ($tmp_arr as $key => $node)
{
if ($i == (count($tag_path) - 1) && is_int($key) &&
$node['name'] == $tag_name)
{
$results[] = $node;
$res = true;
}
elseif (is_int($key) && $node['name'] == $tag_name)
{
$tmp_arr = $node;
$res = true;
break;
}
}
if(!$res)
return false;
}
return $results;
}
I can see a problem if there are several sets of nodes at the same level:
<root>
<container id="1">
<node>a</node>
<node>b</node>
<node>c</node>
<node>d</node>
</container>
<container id="2">
<node>e</node>
<node>f</node>
<node>g</node>
<node>h</node>
</container>
</root>
The function would quit after returning nodes a-d in container 1 and would never reach container 2.
It would require three runs of the function to obtain all 8 nodes. One to get the two container
nodes, then a further two to run those nodes back through the function individually.