7

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?

So I have a html document thus:

<h1> Animals </h1>

Some content goes here.
Some content goes here.

<h2> Mammals </h2>

Some content goes here.
Some content goes here.

<h3> Terrestrial Mammals </h3>
Some content goes here.
Some content goes here.

<h3> Marine Mammals </h3>
Some content goes here.
Some content goes here.

<h4> Whales </h4>
Some content goes here.
Some content goes here.

More specifically, I want a linked table of contents in the form of a nested list of links to headings on the same page:

Table of Contents (automatically generated by PHP code)

  1. Animals
    1. Mammals
      1. Terrestrial_Mammals
      2. Marine_Mammals
        1. Whales
4
  • Shouldn't Mammals be indented and starting with 1? Feb 6, 2011 at 8:25
  • 1
    oops, my bad ! I'll edit my question
    – Manu
    Feb 6, 2011 at 8:45
  • 1
    How is the HTML content generated? Is that static user input? If it’s data (DB, array) with titles being put into the h-tags it’ll be a lot easier then if you only have one string with all that content; then you’ll first have to analyse the string for h-tags.
    – Kissaki
    Feb 6, 2011 at 8:52
  • 1
    the HTML is in a database, it gets in one string variable.
    – Manu
    Feb 6, 2011 at 9:11

7 Answers 7

9

I don't find it elegant, but might help in getting general idea how to create one ;)

It uses simple_html_dom to find and manipulate elements in original html

$htmlcode = <<< EOHTML
<h1> Animals </h1>
Some content goes here.
Some content goes here.
<h2> Mammals </h2>
Some content goes here.
Some content goes here.
<h3> Terrestrial Mammals </h3>
Some content goes here.
Some content goes here.
<h3> Marine Mammals </h3>
Some content goes here.
Some content goes here.
<h4> Whales </h4>
Some content goes here.
Some content goes here.
EOHTML;
// simpehtmldom or other dom manipulating library
require_once 'simple_html_dom.php';

$html = str_get_html($htmlcode);

$toc = '';
$last_level = 0;

foreach($html->find('h1,h2,h3,h4,h5,h6') as $h){
    $innerTEXT = trim($h->innertext);
    $id =  str_replace(' ','_',$innerTEXT);
    $h->id= $id; // add id attribute so we can jump to this element
    $level = intval($h->tag[1]);

    if($level > $last_level)
        $toc .= "<ol>";
    else{
        $toc .= str_repeat('</li></ol>', $last_level - $level);
        $toc .= '</li>';
    }

    $toc .= "<li><a href='#{$id}'>{$innerTEXT}</a>";

    $last_level = $level;
}

$toc .= str_repeat('</li></ol>', $last_level);
$html_with_toc = $toc . "<hr>" . $html->save();
1
  • This post is ancient,... but helpful! When I use this script, I notice that the OL and LI tags do not get closed at the end. I needed to add ` $toc .= str_repeat('</li></ol>', $level );` at the end, outside of the loop.
    – Ideogram
    Mar 24, 2020 at 15:06
7

Here’s an example using DOMDocument:

$doc = new DOMDocument();
$doc->loadHTML($code);

// create document fragment
$frag = $doc->createDocumentFragment();
// create initial list
$frag->appendChild($doc->createElement('ol'));
$head = &$frag->firstChild;
$xpath = new DOMXPath($doc);
$last = 1;

// get all H1, H2, …, H6 elements
foreach ($xpath->query('//*[self::h1 or self::h2 or self::h3 or self::h4 or self::h5 or self::h6]') as $headline) {
    // get level of current headline
    sscanf($headline->tagName, 'h%u', $curr);

    // move head reference if necessary
    if ($curr < $last) {
        // move upwards
        for ($i=$curr; $i<$last; $i++) {
            $head = &$head->parentNode->parentNode;
        }
    } else if ($curr > $last && $head->lastChild) {
        // move downwards and create new lists
        for ($i=$last; $i<$curr; $i++) {
            $head->lastChild->appendChild($doc->createElement('ol'));
            $head = &$head->lastChild->lastChild;
        }
    }
    $last = $curr;

    // add list item
    $li = $doc->createElement('li');
    $head->appendChild($li);
    $a = $doc->createElement('a', $headline->textContent);
    $head->lastChild->appendChild($a);

    // build ID
    $levels = array();
    $tmp = &$head;
    // walk subtree up to fragment root node of this subtree
    while (!is_null($tmp) && $tmp != $frag) {
        $levels[] = $tmp->childNodes->length;
        $tmp = &$tmp->parentNode->parentNode;
    }
    $id = 'sect'.implode('.', array_reverse($levels));
    // set destination
    $a->setAttribute('href', '#'.$id);
    // add anchor to headline
    $a = $doc->createElement('a');
    $a->setAttribute('name', $id);
    $a->setAttribute('id', $id);
    $headline->insertBefore($a, $headline->firstChild);
}

// append fragment to document
$doc->getElementsByTagName('body')->item(0)->appendChild($frag);

// echo markup
echo $doc->saveHTML();
2
  • 1
    I tried this. for the moment it throws a fatalerror on $frag->appendChild
    – Manu
    Feb 6, 2011 at 16:01
  • 1
    this code works only if you do not have a gap in your hierarchy like a h1followed by a h3.
    – olidem
    Jan 23, 2019 at 13:25
5

I found this method, by Alex Freeman (http://www.10stripe.com/articles/automatically-generate-table-of-contents-php.php):

    preg_match_all('#<h[4-6]*[^>]*>.*?<\/h[4-6]>#',$html_string,$resultats);

    //reformat the results to be more usable
    $toc = implode("\n",$resultats[0]);
    $toc = str_replace('<a name="','<a href="#',$toc);
    $toc = str_replace('</a>','',$toc);
    $toc = preg_replace('#<h([4-6])>#','<li class="toc$1">',$toc);
    $toc = preg_replace('#<\/h[4-6]>#','</a></li>',$toc);

    //plug the results into appropriate HTML tags
    $toc = '<div id="toc"> 
    <p id="toc-header">Table des matières</p>
    <hr />
    <ul>
    '.$toc.'
    </ul>
    </div><br /><br />';

    return $toc;

In the HTML, the headers have to be written as:

<h2><a name="target"></a>Text</h2>
5

Combined some of the above to make a nested index of the headings. This function also inserts links into html itself so it can be linked. Pure php no library needed.

   function generateIndex($html)
{
    preg_match_all('/<h([1-6])*[^>]*>(.*?)<\/h[1-6]>/',$html,$matches);

    $index = "<ul>";
    $prev = 2;

    foreach ($matches[0] as $i => $match){

        $curr = $matches[1][$i];
        $text = strip_tags($matches[2][$i]);
        $slug = strtolower(str_replace("--","-",preg_replace('/[^\da-z]/i', '-', $text)));
        $anchor = '<a name="'.$slug.'">'.$text.'</a>';
        $html = str_replace($text,$anchor,$html);

        $prev <= $curr ?: $index .= str_repeat('</ul>',($prev - $curr));
        $prev >= $curr ?: $index .= "<ul>";

        $index .= '<li><a href="#'.$slug.'">'.$text.'</a></li>';

        $prev = $curr;
    }

    $index .= "</ul>";

    return ["html"=>$html,"index"=>$index];
}
0

Have a look at the TOC class. It allows generating table of contents from nested headings. h1 tag can be followed by any lower level h tag. The class uses recursion to extract the headings from article text

0

Short solution using SimpleHTMLDom :

public function getSummary($body) 
{
    $dom  = new Htmldom($body);
    $summ = "<ul>";
    $prev = 2;

    foreach($dom->find("h2,h3,h4") as $x => $htag) 
    {
        $curr = intval(substr($htag->tag, -1));

        $prev <= $curr ?: $summ .= "</ul>";
        $prev >= $curr ?: $summ .= "<ul>";

        $summ .= "<li>$htag->plaintext</li>";

        $prev = $curr;
    }

    $summ .= "</ul>";

    return $summ;
}
0

You have a very simple library for this caseyamcl/toc

$html='<h1>Title</h1>text<h2>...<h2>...';
$tocGenerator = new TOC\TocGenerator();
$toc = $tocGenerator->getHtmlMenu($html);
echo $htmlOut;

Bonus: If you want, he can fix the header without tag id by insert this code before.

$tocGenerator = new TOC\TocGenerator();
$html  = $markupFixer->fix($html);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.