根据标题标签自动生成嵌套目录
你们中哪一位狡猾的程序员可以向我展示一种优雅的 php 编码解决方案,用于根据页面上的标题标签自动生成嵌套目录?
所以我有一个 html 文档:
<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.
更具体地说,我想要一个链接的目录,其形式是同一页面上标题链接的嵌套列表:
目录(由 PHP 代码自动生成)
- 动物
- 哺乳动物
- 陆生哺乳动物
- 海洋哺乳动物
- 鲸鱼
- 哺乳动物
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)
- Animals
- Mammals
- Terrestrial_Mammals
- Marine_Mammals
- Whales
- Mammals
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我觉得它并不优雅,但可能有助于了解如何创建一个;)
它使用 simple_html_dom 来查找并操作原始 html 中的元素
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
以下是使用 DOMDocument 的示例:
Here’s an example using DOMDocument:
我发现了这个方法,作者是 Alex Freeman (http:// /www.10stripe.com/articles/automatically-generate-table-of-contents-php.php):
在 HTML 中,标头必须编写为:
I found this method, by Alex Freeman (http://www.10stripe.com/articles/automatically-generate-table-of-contents-php.php):
In the HTML, the headers have to be written as:
结合上面的一些内容来创建标题的嵌套索引。该函数还将链接插入到 html 本身中,以便可以链接。纯php,无需库。
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.
查看TOC 类。它允许从嵌套标题生成目录。 h1 标签后面可以跟任何较低级别的 h 标签。该类使用递归从文章文本中提取标题
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
使用 SimpleHTMLDom 的简短解决方案:
Short solution using SimpleHTMLDom :
你有一个非常简单的库 caseyamcl/toc
奖金:如果你愿意,他可以修复标题之前插入此代码,无需标记 id。
You have a very simple library for this caseyamcl/toc
Bonus: If you want, he can fix the header without tag id by insert this code before.