4 * Creates a TOC (table of contents) from a given HTML file.
5 * <h1> is ignored; all other headings are used.
7 * @author Christian Weiske <cweiske@cweiske.de>
9 * Alternative if you have an XSLT 2 processor: http://xmlplease.com/tocxhtml
12 echo "Please pass a file\n";
16 if (!file_exists($file)) {
17 echo "File does not exist: $file\n";
20 if (substr($file, -4) != '.htm') {
21 echo "build-toc.php works only on htm files\n";
25 $sx = simplexml_load_file($file);
27 echo "Failed to load XML\n";
32 $body->registerXPathNamespace('h', 'http://www.w3.org/1999/xhtml');
33 $elems = $body->xpath(
36 . 'self::h:h2 or self::h:h3 or self::h:h4 or self::h:h5 or self::h:h6'
38 . ' or self::h2 or self::h3 or self::h4 or self::h5 or self::h6'
44 foreach ($elems as $elem) {
45 $name = $elem->getName();
46 $level = (int) $name{1};
47 $data[] = (object) array(
48 'title' => (string) $elem,
49 'id' => (string) $elem['id'],
54 $data[$n - 1]->nextLevel = $level;
58 $html = "<ul class=\"toc\">\n";
59 foreach ($data as $h) {
60 $i = str_repeat(' ', ($h->level -1) * 2 - 1);
62 . '<li><a href="#' . $h->id . '">'
63 . htmlspecialchars($h->title)
65 if ($h->nextLevel > $h->level) {
67 . $i . ' <ul>' . "\n";
69 $html .= '</li>' . "\n";
71 if ($h->nextLevel < $h->level) {
72 $html .= substr($i, 0, -1) . "</ul>\n"
73 . substr($i, 0, -2) . "</li>\n";