[PHP] How to Generate Dynamic Table of Contents

table of contents


In this article, we will describe about how to automatically generate Table of Contents from headings using PHP.
Our method also supports multiple levels of headings.



Goal of this article

We aim to automatically generate a table of contents from headings using PHP, assuming the presence of HTML as below.
The table of contents will be inserted just before the first heading tag.

<div id="content">
    <h2>heading1</h2>
    <h3>subheading1</h3>
    <h3>subheading2</h3>
    <h4>sub-subheading1</h4>
    <h5>sub-sub-subheading1</h5>
    <h3>subheading3</h3>
    <h2>heading2</h2>
    <h3>subheading1</h3>
</div>


If you want to automatically generate a table of contents in PHP, you need to have the content written in a separate file. Here, we’ve named the file content.php.





PHP code to generate a table of contents

The PHP for automatically generating a table of contents from headings is as follows.
It also provides anchor links to enable jumping from the table of contents to the headings.

$content = file_get_contents('./content.php');  // get the contents
$content = autoTableOfContents($content);       // automatically generate table of contents
echo $content;                                  // show the contents


function autoTableOfContents($content) {
    $target = ['h2','h3','h4','h5'];
    $pattern = '/<('.implode('|', $target).')([^>]*)>(.*?)<\/h\d>/';

    if(preg_match_all($pattern, $content, $matches, PREG_SET_ORDER)){
        $toc = '<div id="toc"><p>Table of Contents</p><ul>';
        foreach($matches as $i => $match){
            $id = "toc-$i";                                                     // ID for anchor link
            list($h_tag, $h_name, $h_attr, $h_text) = $match;                   // heading tag,heading name,heading attribute、heading text
            $new_tag = "<$h_name id='$id' $h_attr>$h_text</$h_name>";           // Generate heading tag with ID.
            $content = preg_replace("{".$h_tag."}", $new_tag, $content, 1);     // replace to the new heading tag           
            $toc .= "<li class='toc-$h_name'><a href='#$id'>$h_text</a></li>";  // add list of table of contents
        }
        $toc .='</ul></div>';
        $content = preg_replace("/(<$target[0])/", "$toc$1", $content, 1);      // add table of contents before the first heading
    }
    return $content;
}





In the case of WordPress

In the case of WordPress, you can write the previous autoTableOfContents function in the functions.php file and use a filter hook in the output location of the content.

add_filter('the_content', 'autoTableOfContents');
the_content();





Clarify the hierarchy of the table of contents

All that’s left is to style it as you like. I’ll provide a sample CSS.
Tthe previous script have added classes like “toc-H3” to the list elements of the table of contents, making it easier to style hierarchically.

#toc .toc-H3 { margin-left: 15px }
#toc .toc-H4 { margin-left: 30px }
#toc .toc-H5 { margin-left: 45px }
#toc .toc-H6 { margin-left: 60px }
#toc {
    border: 3px #BDBDBD solid;
    padding: 30px;
    margin: 50px 0;
}
#toc p {
    font-weight: bold;
    font-size: 24px;
    margin-bottom: 10px;
}
#toc a{
    font-size: 16px;
    color: inherit;
}
#toc ul {
    padding-left: 20px;
}
#toc li {
    line-height: 1.8;
}





Include only h2 in the table of contents

Earlier, we included headings from h2 to h5 in the table of contents.
You can adjust which heading levels to include by modifying the following part of the JavaScript as needed.

$target = ['h2','h3','h4','h5'];







That is all, it was about how to automatically generate Table of Contents from headings using PHP!

Sponsored Link

You can subscribe by SNS

Sponcerd Link

Leave a Reply

*