哪位狡猾的程序员可以向我展示一个优雅的PHP编码解决方案,用于根据页面上的标题标签自动生成嵌套的目录?
所以我有一个html文件:
Animals
Some content goes here.
Some content goes here.
Mammals
Some content goes here.
Some content goes here.
Terrestrial Mammals
Some content goes here.
Some content goes here.
Marine Mammals
Some content goes here.
Some content goes here.
Whales
Some content goes here.
Some content goes here.
更具体地说,我想要一个链接的目录,其形式是在同一页面上的标题链接的嵌套列表:
目录(由PHP代码自动生成)
>动物
>哺乳动物
> Terrestrial_Mammals
> Marine_Mammals
>鲸鱼
解决方法:
我觉得它不优雅,但可能有助于大致了解如何创建一个;)
它使用simple_html_dom来查找和操作原始html中的元素
$htmlcode = <<< EOHTML
Animals
Some content goes here.
Some content goes here.
Mammals
Some content goes here.
Some content goes here.
Terrestrial Mammals
Some content goes here.
Some content goes here.
Marine Mammals
Some content goes here.
Some content goes here.
Whales
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 .= "
- ";
else{
$toc .= str_repeat('
', $last_level - $level);$toc .= '';
}
$toc .= "
{$innerTEXT}";$last_level = $level;
}
$toc .= str_repeat('
', $last_level);$html_with_toc = $toc . "
" . $html->save();
标签:dynamically-generated,php
来源: https://codeday.me/bug/20190929/1830215.html