title: In PHP DOM get Element/Node depth in recursive function
body: <p>I have the following function, which reads all child elements/text nodes of a given dom element into an array, by recursively calling itself.</p>
  
  <p>It works fine, but I need the depth of each node (text or element) in relation to the first(!) given DOM node before any recursion happened. I can't figure out how to do this, any ideas?</p>
  
  <pre><code>function recursively_find_text_nodes($dom_element) {
  
      $return = array();
  
      foreach ($dom_element-&gt;childNodes as $dom_child) {
  
          switch ($dom_child-&gt;nodeType) {
  
              case XML_TEXT_NODE:
  
                  if (trim($dom_child-&gt;nodeValue) !== '') {                
  
                      $return[] = $dom_child-&gt;nodeValue;
  
                  }
  
              break;
  
              case XML_ELEMENT_NODE:
  
                  $return = array_merge($return, $this-&gt;recursively_find_text_nodes($dom_child));
  
              break;
  
          }
  
      }
  
      return $return;
  
  }
  </code></pre>
  
  <p>I am parsing an XML node with this function. It can have any number of elements and subelements. The idea is that I +1 a depth variable, every time the function goes into recursion. the problem is that when I am in a node that actually does not go deeper, but up in the tree I'd have to -1 the variable. So for every node that I am currently in I would need the depth of the current element in regard to the DOM node that was passed to the function before(!) it went into recursion.  </p>