The*_*ebs 3 php tableofcontents
我希望在 php 中创建一个非常简单、非常基本的嵌套目录,它可以获取所有 h1-6 并适当缩进内容。这意味着如果我有类似的东西:
<h1>content</h1>
<h2>more content</h2>
Run Code Online (Sandbox Code Playgroud)
我应该得到:
content
more content.
Run Code Online (Sandbox Code Playgroud)
我知道将由 css 创建缩进,这很好,但是如何创建一个包含指向页面内容的工作链接的目录?
显然很难理解我的要求......
我要求一个读取 html 文档并提取所有 h1-6 并制作目录的函数。
我使用了这个包,使用起来非常简单直接。
https://github.com/caseyamcl/toc
通过在您的composer.json文件中包含以下内容来通过Composer安装:
{
"require": {
"caseyamcl/toc": "^3.0",
}
}
Run Code Online (Sandbox Code Playgroud)
或者,将 src 文件夹放入您的应用程序中并使用 PSR-4 自动加载器来包含这些文件。
用法 该包包含两个主要类:
TOC\MarkupFixer:将 id 锚点属性添加到任何还没有的 H1...H6 标记(您可以指定在运行时使用哪些标头标记级别) TOC\TocGenerator:从 HTML 标记生成目录 基本示例:
$myHtmlContent = <<<END
<h1>This is a header tag with no anchor id</h1>
<p>Lorum ipsum doler sit amet</p>
<h2 id='foo'>This is a header tag with an anchor id</h2>
<p>Stuff here</p>
<h3 id='bar'>This is a header tag with an anchor id</h3>
END;
$markupFixer = new TOC\MarkupFixer();
$tocGenerator = new TOC\TocGenerator();
// This ensures that all header tags have `id` attributes so they can be used as anchor links
$htmlOut = "<div class='content'>" . $markupFixer->fix($myHtmlContent) . "</div>";
//This generates the Table of Contents in HTML
$htmlOut .= "<div class='toc'>" . $tocGenerator->getHtmlMenu($myHtmlContent) . "</div>";
echo $htmlOut;
Run Code Online (Sandbox Code Playgroud)
这会产生以下输出:
<div class='content'>
<h1 id="this-is-a-header-tag-with-no-anchor-id">This is a header tag with no anchor id</h1>
<p>Lorum ipsum doler sit amet</p>
<h2 id="foo">This is a header tag with an anchor id</h2>
<p>Stuff here</p>
<h3 id="bar">This is a header tag with an anchor id</h3>
</div>
<div class='toc'>
<ul>
<li class="first last">
<span></span>
<ul class="menu_level_1">
<li class="first last">
<a href="#foo">This is a header tag with an anchor id</a>
<ul class="menu_level_2">
<li class="first last">
<a href="#bar">This is a header tag with an anchor id</a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6671 次 |
| 最近记录: |