Dynamically creating nested DIVs in PHP - php

I would like to create nested divs dynamically, preferably without JavaScript.
So if you have n number of DIVs, DIV1 contains DIV1 which contains DIV3 etc…
How would I code that in PHP?

function recursiveDiv($num) {
$html = '<div id="div'.$num.'">%s</div>';
for($i = $num - 1; $i >= 1; $i--) {
$html = '<div id="div'.$i.'">'.$html.'</div>';
}
return $html;
}
echo sprintf(recursiveDiv(5), 'Hello World');
Untested but should give you want you want.

Here is a simple loop example using $n = 3. You can change $n to any number and it will nest div tags for you. I'm not entirely sure why you would want to do this, but here it is.
$openingTags = '';
$closingTags = '';
$n = 3;
for ($i = 0; $i < $n; ++$i) {
$openingTags .= '<div id="div' . $i . '">';
$closingTags .= '</div>';
}
echo $openingTags . 'Hello World' . $closingTags;

This code should allow you to create the nested divs and also populate them with content. Replaced orginal code with below, this should work but its untested
$result = mysql_query("SELECT * FROM table");
$count = mysql_num_rows($result);
$html = '';
$end_html = '';
while($row = mysql_fetch_object($result)){
$html .= '<div id="div'.$count.'">'.$row->textfield; # any database column
$end_html .= '</div>';
$count--;
}
echo $html . $end_html;

While others are suggesting using mathematical solutions based on for loops, you can do this a bit more explicitly—clearly setting classnames—by using an array like this:
// Set the DIVs array.
$divs_array = array();
$divs_array[] = 'DIV1';
$divs_array[] = 'DIV2';
$divs_array[] = 'DIV3';
Now with that array set, you can use implode to take the content of those arrays and set them as DIV class values like this. Note the implode logic might seem confusing, but look at what it creates and look at how the code is set and it makes more sense after a while:
// Set the DIVs.
$div_opening = $div_closing = '';
if (!empty($divs_array)) {
$div_opening = '<div class="' . implode($divs_array, '">' . "\n" . '<div class="') . '">';
$div_closing = '</div><!-- .' . implode(array_reverse($divs_array), '-->' . "\n" . '</div><!-- .') . ' -->';
}
And then you can set the content between the $div_opening and $div_closing values like this:
// Return the content wrapped in the DIVs.
echo $div_opening
. '<p>Hello world.</p>'
. $div_closing
;
The output would be something like this:
<div class="DIV1">
<div class="DIV2">
<div class="DIV3">
<p>Hello world.</p>
</div><!-- .DIV3 -->
</div><!-- .DIV2 -->
</div><!-- .DIV1 -->
Note my personal coding style is to—whenever possible—set comments after each DIV that clearly shows what that </div> is actually closing. So that is what the comments like <!-- .DIV3 --> refer to; feel free to adjust to fit your own coding needs and style.

Related

Auto increment through a php loop

I have a case where I am using the code below to populate a template of sorts. Within the templates' javascript I would individually check the data attribute field I setup, essentially causing me to have multiple JS files instead of one that is shared. I then thought I could use a generic name field too, but prepend a number through the loop.
For example, with the line of code below where the `name="testField". I want to see if there is a way that I can add a number, but auto increment it through the loop with php.
Is this possible?
echo '<div class="markerItem" name="testField' . $number . '" "data-marker="' . $marker_data . '">';
PHP Code
if ($marker_stmt = $con->prepare($sql_marker)) {
$marker_stmt->execute();
$marker_rows = $marker_stmt->fetchAll(PDO::FETCH_ASSOC);
echo '<div id="projMarker">';
foreach ($marker_rows as $marker_row) {
$marker_solution = $marker_row['solution'];
$maker_item = $marker_row['subSolution'];
$marker_data = $marker_row['subSolution'];
echo '<div class="markerItem" data-marker="' . $marker_data . '">';
echo $marker_item;
echo '</div>';
}
}
echo '</div>';
if ($marker_stmt = $con->prepare($sql_marker)) {
$marker_stmt->execute();
$marker_rows = $marker_stmt->fetchAll(PDO::FETCH_ASSOC);
echo '<div id="projMarker">';
foreach ($marker_rows as $key=>$marker_row) {
$marker_solution = $marker_row['solution'];
$maker_item = $marker_row['subSolution'];
$marker_data = $marker_row['subSolution'];
echo '<div class="markerItem" name="testField_'.$key.'" data-marker="' . $marker_data . '">';
echo $marker_item;
echo '</div>';
}
}
echo '</div>';
Using this, $key is assigned from the array index which will be a number starting from 0 and ending at count($marker_rows)-1.
Suprisingly, I couldn't find an appropriate duplicate for this.
You can easily increment or decrement variables in PHP.
$number = 0;
foreach ($marker_rows as $marker_row) {
...
$number++; // $number will now be $number+1
}
You can use $number++ directly in your attribute (if concatenating) as this will return the current $number then increment the value.

PHP wrap two render arrays in separate divs

I need to wrap both my arrays in their own wrapping div outside of the foreach loop.
function foo() {
//my foreach loops
$top_content[] = $top;
$bottom_content[] = $bottom;
return array($top_content, $bottom_content);
}
Ideally I would be able to:
function foo() {
//my foreach loops
$top_content[] = '<div class="wrapper-one">' . $top . '</div>';
$bottom_content[] = '<div class="wrapper-two">' . $bottom . '</div>';
return array($top_content, $bottom_content);
}
but then I get an error of: Notice: Array to string conversion
any help appreciated.
function foo() {
//my foreach loops
$top_content[0] = '<div class="wrapper-one">' . $top . '</div>';
$bottom_content[0] = '<div class="wrapper-two">' . $bottom . '</div>';
return array($top_content, $bottom_content);
}
This is so because you are trying to concatenate array with string. Since $top and $bottom could have been initialized as array before.
$top_content[0] = '<div class="wrapper-one">' . $top . '</div>';
$bottom_content[] = '<div class="wrapper-two">' . $bottom . '</div>';
So my guess is you must be doing creating $top and $bottom as array and trying to concatenate at the end of for-each loop.
You can still do it like this.
$topContents = implode('', $top);
$bottomContents = implode('', $bottom);
$top_content[0] = '<div class="wrapper-one">' . $topContents . '</div>';
$bottom_content[] = '<div class="wrapper-two">' . $bottom . '</div>';
The trick is to use php's implode function to concatenate array first. After concatenation it returns string. This string can then further be concatenated with other strings.
Give it a try and let us know.

Creating a table of contents in php

I am looking to create a very simple, very basic nested table of contents in php which gets all the h1-6 and indents things appropriately. This means that if I have something like:
<h1>content</h1>
<h2>more content</h2>
I should get:
content
more content.
I know it will be css that creates the indents, that's fine, but how do I create a table of contents with working links to the content on the page?
apparently its hard to grasp what I am asking for...
I am asking for a function that reads an html document and pulls out all the h1-6 and makes a table of contents.
I used this package, it's pretty easy and straight forward to use.
https://github.com/caseyamcl/toc
Install via Composer by including the following in your composer.json file:
{
"require": {
"caseyamcl/toc": "^3.0",
}
}
Or, drop the src folder into your application and use a PSR-4 autoloader to include the files.
Usage
This package contains two main classes:
TOC\MarkupFixer: Adds id anchor attributes to any H1...H6 tags that do not already have any (you can specify which header tag levels to use at runtime)
TOC\TocGenerator: Generates a Table of Contents from HTML markup
Basic Example:
$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;
This produces the following output:
<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">
This is a header tag with an anchor id
<ul class="menu_level_2">
<li class="first last">
This is a header tag with an anchor id
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
For this you have just to search for the tags in the HTML code.
I wrote two functions (PHP 5.4.x).
The first one returns an array, that contains the data of the table of contents. The data is is only the headline it self, the id of the tag (if you want to use anchors) and a sub-table of content.
function get_headlines($html, $depth = 1)
{
if($depth > 7)
return [];
$headlines = explode('<h' . $depth, $html);
unset($headlines[0]); // contains only text before the first headline
if(count($headlines) == 0)
return [];
$toc = []; // will contain the (sub-) toc
foreach($headlines as $headline)
{
list($hl_info, $temp) = explode('>', $headline, 2);
// $hl_info contains attributes of <hi ... > like the id.
list($hl_text, $sub_content) = explode('</h' . $depth . '>', $temp, 2);
// $hl contains the headline
// $sub_content contains maybe other <hi>-tags
$id = '';
if(strlen($hl_info) > 0 && ($id_tag_pos = stripos($hl_info,'id')) !== false)
{
$id_start_pos = stripos($hl_info, '"', $id_tag_pos);
$id_end_pos = stripos($hl_info, '"', $id_start_pos);
$id = substr($hl_info, $id_start_pos, $id_end_pos-$id_start_pos);
}
$toc[] = [ 'id' => $id,
'text' => $hl_text,
'sub_toc' => get_headlines($sub_content, $depth + 1)
];
}
return $toc;
}
The second returns a string that formats the toc with HTML.
function print_toc($toc, $link_to_htmlpage = '', $depth = 1)
{
if(count($toc) == 0)
return '';
$toc_str = '';
if($depth == 1)
$toc_str .= '<h1>Table of Content</h1>';
foreach($toc as $headline)
{
$toc_str .= '<p class="headline' . $depth . '">';
if($headline['id'] != '')
$toc_str .= '<a href="' . $link_to_htmlpage . '#' . $headline['id'] . '">';
$toc_str .= $headline['text'];
$toc_str .= ($headline['id'] != '') ? '</a>' : '';
$toc_str .= '</p>';
$toc_str .= print_toc($headline['sub_toc'], $link_to_htmlpage, $depth+1);
}
return $toc_str;
}
Both functions are far away from being perfect, but they work fine in my tests. Feel free to improve them.
Notice: get_headlines is not a parser, so it does not work on broken HTML code and just crashes. It also only works with lowercase <hi>-tags.
How about this (although it can only do one H level) ...
function getTOC(string $html, int $level=1) {
$toc="";
$x=0;
$n=0;
$html1="";
$safety=1000;
while ( $x>-1 and $safety-->0 ) {
$html0=strtolower($html);
$x=strpos($html0, "<h$level");
if ( $x>-1 ) {
$y=strpos($html0, "</h$level>");
$part=strip_tags(substr($html, $x, $y-$x));
$toc .="<a href='#head$n'>$part</a>\n";
$html1.=substr($html,0,$x)."<a name='head$n'></a>".substr($html, $x, $y-$x+5)."\n";
$html=substr($html, $y+5);
$n++;
}
}
$html1.=$html;
$html=$toc."\n<HR>\n".$html1;
return $html;
}
This will create a basic list of links
$html="<html><body>";
$html.="<h1>Heading 1a</h1>One Two Three";
$html.="<h2>heading 2a</h2>Four Five Six";
$html.="<h1 class='something'>Heading 1b</h1>Seven Eight Nine";
$html.="<h2>heading 2b</h2>Ten Eleven Twelve";
$html.="</body></html>";
echo getTOC($html, 1);
gives...
<a href='#head0'>Heading 1a</a>
<a href='#head1'>Heading 1b</a>
<HR>
<html><body><a name='head0'></a><h1>Heading 1a</h1>
One Two Three<h2>heading 2a</h2>Four Five Six<a name='head1'></a><h1
class='something'>Heading 1b</h1>
Seven Eight Nine<h2>heading 2b</h2>Ten Eleven Twelve</body></html>
See https://onlinephp.io/c/fceb0 for a running example
This function return the string with appended table of content only for h2 tags. 100% tested code.
function toc($str){
$html = preg_replace('/]+\>/i', '$0 In This Article', $str, 1); //toc just after first image in content
$doc = new DOMDocument();
$doc->loadHTML($html);
// create document fragment
$frag = $doc->createDocumentFragment();
// create initial list
$frag->appendChild($doc->createElement('ul'));
$head = &$frag->firstChild;
$xpath = new DOMXPath($doc);
$last = 1;
// get all H1, H2, …, H6 elements
$tagChek = array();
foreach ($xpath->query('//*[self::h2]') as $headline) {
// get level of current headline
sscanf($headline->tagName, 'h%u', $curr);
array_push($tagChek,$headline->tagName);
// move head reference if necessary
if ($curr parentNode->parentNode;
}
} elseif ($curr > $last && $head->lastChild) {
// move downwards and create new lists
for ($i=$last; $ilastChild->appendChild($doc->createElement('ul'));
$head = &$head->lastChild->lastChild;
}
}
$last = $curr;
// add list item
$li = $doc->createElement('li');
$head->appendChild($li);
$a = $doc->createElement('a', $headline->textContent);
$head->lastChild->appendChild($a);
// build ID
$levels = array();
$tmp = &$head;
// walk subtree up to fragment root node of this subtree
while (!is_null($tmp) && $tmp != $frag) {
$levels[] = $tmp->childNodes->length;
$tmp = &$tmp->parentNode->parentNode;
}
$id = 'sect'.implode('.', array_reverse($levels));
// set destination
$a->setAttribute('href', '#'.$id);
// add anchor to headline
$a = $doc->createElement('a');
$a->setAttribute('name', $id);
$a->setAttribute('id', $id);
$headline->insertBefore($a, $headline->firstChild);
}
// echo $frag;
// append fragment to document
if(!empty($tagChek)):
$doc->getElementsByTagName('section')->item(0)->appendChild($frag);
return $doc->saveHTML();
else:
return $str;
endif;
}

How can I add a list of links to images to several dynamically generated divs (via PHP)?

I'm new to PHP and I just figured out how to generate content from several arrays to populate 40 divs. It's a product gallery and the different parts are generated via a for loop. Each time through the loop, I'm using the index to not only grab info from the arrays, but also to create a link for the entire div that I want to use as a JQuery Lightbox to show different views of each product. I've already been able to create a link to the first of the images. I've been trying to use the scandir() function, readdir() function to get a list of each image, but I haven't had any success. The images are in folders, _images/products/0/0.jpg (this folder also contains 1.jpg, 2.jpg, etc. Each time through the loop, it changes to _images/products/1/0.jpg - there are more images in this folder too. I need to create a link for each image and add it to the array in a way that will link a distinct Lightbox with each div.
$names = array ('item1', 'item2', 'item3', etc...);
$prices = array ('item1', 'item2', 'item3', etc...);
$number = array ('item1', 'item2', 'item3', etc...);
$serves = array ('item1', 'item2', 'item3', etc...);
$names_size = sizeof($names)
$img_link = "_images/products/"; // used to create the link for $div2
$div1 = "<div id=\"";
$div2 = "\" class=\"products grid_3\"><a href=\"";
$div3 = "\"><h3 class=\"name\">";
$hero_img = "</h3><img class=\"hero\" src=\"_images/heros/";
$li_price = "<ul><li>Price: <span class=\"price\">$";
$li_serves = "<li>Serves: <span class=\"serves\">";
$li_num = "<li>KC# <span class=\"kcnum\">";
$li_close = "</span></li>";
$div4 = "</ul></a></div>";
for ($i = 0; $i < $names_size; $i++) {
$div = $div1 . $names[$i] . $div2 . $img_link . $i . "/0.jpg" . $div3 . ucwords($names[$i]) . $hero_img . $i . ".jpg\" alt=\"" . ucwords($names[$i]) . "\" />";
$div .= $li_price . $prices[$i] . $li_close;
$div .= $li_kc_num . $kc_no[$i] . $li_close;
$div .= $li_serves . $serves[$i] . $li_close;
$div .= $div4;
echo "{$div}" . "\n";
}
The problem I'm having is that before I echo the final $div, I need to add a list of links for the specific product so I can use make the lightbox work for each div. I tried inserting the code (below) just before echoing the completed $div, but I couldn't go any further with it.
$gallery_array = array();
$files = scandir($img_link . $i);
foreach($files as $file) {
array_push($gallery_array, $file);
}
$gallery_array_size = sizeof($gallery_array);
I honestly don't even know if the Lightbox can even work like this. Any ideas?
You don't have to create a $div like that. You can mix php and HTML codes together.
Your $gallery_array is the same as the $files.
<?php
$names = array ('item1', 'item2', 'item3');
$prices = array ('item1', 'item2', 'item3');
$kc_no = array ('item1', 'item2', 'item3');
$serves = array ('item1', 'item2', 'item3');
$names_size = sizeof($names);
$img_link = "_images/products/";
for ($i = 0; $i < $names_size; $i++) {
?>
<div id="<?=$names[$i]?>" class="products grid_3">
<a href="<?=$img_link.$i?>/0.jpg">
<h3 class="name"><?=ucwords($names[$i])?></h3>
<img class="hero" src="_images/heros/<?=$i?>.jpg" alt="<?=ucwords($names[$i])?>" />
<ul>
<li>Price: <span class="price">$<?=$prices[$i]?></span></li>
<li>KC# <span class="kcnum"><?=$kc_no[$i]?></span></li>
<li>Serves: <span class="serves"><?=$serves[$i]?></span></li>
</ul>
<span>Gallery</span>
<ul>
<?php
$files = scandir($img_link . $i);
for ($x = 2; $x < sizeof($files); $x++) {
echo "<li>".$files[$x]."</li>";
}
?>
</ul>
</a>
</div>
<?php
}
?>

Automatically generate nested table of contents based on heading tags

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
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
$htmlcode = <<< EOHTML
<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.
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 .= "<ol>";
else{
$toc .= str_repeat('</li></ol>', $last_level - $level);
$toc .= '</li>';
}
$toc .= "<li><a href='#{$id}'>{$innerTEXT}</a>";
$last_level = $level;
}
$toc .= str_repeat('</li></ol>', $last_level);
$html_with_toc = $toc . "<hr>" . $html->save();
Here’s an example using DOMDocument:
$doc = new DOMDocument();
$doc->loadHTML($code);
// create document fragment
$frag = $doc->createDocumentFragment();
// create initial list
$frag->appendChild($doc->createElement('ol'));
$head = &$frag->firstChild;
$xpath = new DOMXPath($doc);
$last = 1;
// get all H1, H2, …, H6 elements
foreach ($xpath->query('//*[self::h1 or self::h2 or self::h3 or self::h4 or self::h5 or self::h6]') as $headline) {
// get level of current headline
sscanf($headline->tagName, 'h%u', $curr);
// move head reference if necessary
if ($curr < $last) {
// move upwards
for ($i=$curr; $i<$last; $i++) {
$head = &$head->parentNode->parentNode;
}
} else if ($curr > $last && $head->lastChild) {
// move downwards and create new lists
for ($i=$last; $i<$curr; $i++) {
$head->lastChild->appendChild($doc->createElement('ol'));
$head = &$head->lastChild->lastChild;
}
}
$last = $curr;
// add list item
$li = $doc->createElement('li');
$head->appendChild($li);
$a = $doc->createElement('a', $headline->textContent);
$head->lastChild->appendChild($a);
// build ID
$levels = array();
$tmp = &$head;
// walk subtree up to fragment root node of this subtree
while (!is_null($tmp) && $tmp != $frag) {
$levels[] = $tmp->childNodes->length;
$tmp = &$tmp->parentNode->parentNode;
}
$id = 'sect'.implode('.', array_reverse($levels));
// set destination
$a->setAttribute('href', '#'.$id);
// add anchor to headline
$a = $doc->createElement('a');
$a->setAttribute('name', $id);
$a->setAttribute('id', $id);
$headline->insertBefore($a, $headline->firstChild);
}
// append fragment to document
$doc->getElementsByTagName('body')->item(0)->appendChild($frag);
// echo markup
echo $doc->saveHTML();
I found this method, by Alex Freeman (http://www.10stripe.com/articles/automatically-generate-table-of-contents-php.php):
preg_match_all('#<h[4-6]*[^>]*>.*?<\/h[4-6]>#',$html_string,$resultats);
//reformat the results to be more usable
$toc = implode("\n",$resultats[0]);
$toc = str_replace('<a name="','<a href="#',$toc);
$toc = str_replace('</a>','',$toc);
$toc = preg_replace('#<h([4-6])>#','<li class="toc$1">',$toc);
$toc = preg_replace('#<\/h[4-6]>#','</a></li>',$toc);
//plug the results into appropriate HTML tags
$toc = '<div id="toc">
<p id="toc-header">Table des matières</p>
<hr />
<ul>
'.$toc.'
</ul>
</div><br /><br />';
return $toc;
In the HTML, the headers have to be written as:
<h2><a name="target"></a>Text</h2>
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.
function generateIndex($html)
{
preg_match_all('/<h([1-6])*[^>]*>(.*?)<\/h[1-6]>/',$html,$matches);
$index = "<ul>";
$prev = 2;
foreach ($matches[0] as $i => $match){
$curr = $matches[1][$i];
$text = strip_tags($matches[2][$i]);
$slug = strtolower(str_replace("--","-",preg_replace('/[^\da-z]/i', '-', $text)));
$anchor = '<a name="'.$slug.'">'.$text.'</a>';
$html = str_replace($text,$anchor,$html);
$prev <= $curr ?: $index .= str_repeat('</ul>',($prev - $curr));
$prev >= $curr ?: $index .= "<ul>";
$index .= '<li>'.$text.'</li>';
$prev = $curr;
}
$index .= "</ul>";
return ["html"=>$html,"index"=>$index];
}
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
Short solution using SimpleHTMLDom :
public function getSummary($body)
{
$dom = new Htmldom($body);
$summ = "<ul>";
$prev = 2;
foreach($dom->find("h2,h3,h4") as $x => $htag)
{
$curr = intval(substr($htag->tag, -1));
$prev <= $curr ?: $summ .= "</ul>";
$prev >= $curr ?: $summ .= "<ul>";
$summ .= "<li>$htag->plaintext</li>";
$prev = $curr;
}
$summ .= "</ul>";
return $summ;
}
You have a very simple library for this caseyamcl/toc
$html='<h1>Title</h1>text<h2>...<h2>...';
$tocGenerator = new TOC\TocGenerator();
$toc = $tocGenerator->getHtmlMenu($html);
echo $htmlOut;
Bonus: If you want, he can fix the header without tag id by insert this code before.
$tocGenerator = new TOC\TocGenerator();
$html = $markupFixer->fix($html);

Categories