Skip to content

Instantly share code, notes, and snippets.

@billcreswell
Forked from miwebguy/PHPTableOfContents.php
Created June 26, 2014 01:50
Show Gist options
  • Save billcreswell/e848caddd708708cd4dc to your computer and use it in GitHub Desktop.
Save billcreswell/e848caddd708708cd4dc to your computer and use it in GitHub Desktop.
<?php
/**
* Use whatever method you like to grab your HTML string. We'll use a site I mentioned in this post
* as an example.
*/
$remote_site_data = file_get_contents('http://www.10stripe.com/articles/automatically-generate-table-of-contents-php.php');
$dom_document = new DomDocument();
@$dom_document->loadHTML($remote_site_data);
$headers = $dom_document->getElementsByTagName('h2');
foreach ($headers as $header) {
$table_of_contents[] = trim($header->nodeValue);
}
var_dump($table_of_contents);
/**
array(5) {
[0]=>
string(10) "Motivation"
[1]=>
string(11) "This script"
[2]=>
string(12) "How it works"
[3]=>
string(3) "Fin"
[4]=>
string(17) "About the Author"
}
*/
/* Pull out one class
foreach ($headers as $header) {
if ($header->getAttribute('class') == 'specialclassname') {
$table_of_contents[] = trim($header->nodeValue);
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment