PHP code example of baraja-core / table-of-content

1. Go to this page and download the library: Download baraja-core/table-of-content library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

baraja-core / table-of-content example snippets


use Baraja\TableOfContent\ContentManager;

$manager = new ContentManager();

$html = '
<h1>PHP Online Course for Beginners</h1>
<p>PHP is a server-side scripting language designed for modern web applications.</p>
<h2>How to Start?</h2>
<p>First, you need to install PHP on your computer...</p>
<h2>Basic Software</h2>
<p>You will need a code editor and a local server...</p>
<h2>License</h2>
<p>This course is released under MIT license.</p>
';

$response = $manager->parse($html);

// Get the title extracted from <h1>
$title = $response->getTitle();
// Result: "PHP Online Course for Beginners"

// Get the perex extracted from the first <p>
$perex = $response->getPerex();
// Result: "PHP is a server-side scripting language designed for modern web applications."

// Get all table of content items (ID => Title)
$items = $response->getItems();
// Result:
// [
//     'how-to-start' => 'How to Start?',
//     'basic-software' => 'Basic Software',
//     'licence' => 'License',
// ]

// Get modified content with anchor elements
$content = $response->getContent();

// Get content without the <h1> tag (useful for separate title rendering)
$pureContent = $response->getPureContent();

// Get the original unmodified HTML
$original = $response->getOriginal();

$items = $response->getItems();

echo '<nav class="table-of-contents">';
echo '<h3>Contents:</h3>';
echo '<ol>';
foreach ($items as $id => $title) {
    echo sprintf('<li><a href="#%s">%s</a></li>', $id, htmlspecialchars($title));
}
echo '</ol>';
echo '</nav>';

$response = $manager->parse($html);

// Both of these are equivalent:
echo $response;
echo $response->getContent();

public function __construct(
    private ContentManager $contentManager,
) {
}