title: Automatically generate nested table of contents based on heading tags
body: <p>Which one of you crafty programmers can show me an elegant php coded solution for automatically generating a nested table of contents based on heading tags on the page?</p>
  
  <p>So I have a html document thus:</p>
  
  <pre><code>&lt;h1&gt; Animals &lt;/h1&gt;
  
  Some content goes here.
  Some content goes here.
  
  &lt;h2&gt; Mammals &lt;/h2&gt;
  
  Some content goes here.
  Some content goes here.
  
  &lt;h3&gt; Terrestrial Mammals &lt;/h3&gt;
  Some content goes here.
  Some content goes here.
  
  &lt;h3&gt; Marine Mammals &lt;/h3&gt;
  Some content goes here.
  Some content goes here.
  
  &lt;h4&gt; Whales &lt;/h4&gt;
  Some content goes here.
  Some content goes here.
  </code></pre>
  
  <p>More specifically, I want a linked table of contents in the form of a nested list of links to headings on the same page:</p>
  
  <p>Table of Contents (automatically generated by PHP code)</p>
  
  <ol>
  <li>Animals
  <ol>
  <li>Mammals
  <ol>
  <li>Terrestrial_Mammals</li>
  <li>Marine_Mammals
  <ol>
  <li>Whales</li>
  </ol></li>
  </ol></li>
  </ol></li>
  </ol>