Search code examples
phpfunctiontitlepage-title

How to get title from html file using directory - php


Fairly new to php, so bear with me. I'm trying to figure out how to read a directory/folder and return both the filename/path and the title of that file into a li.

$handle = opendir('.'); 
while (false !== ($file = readdir($handle))){ 
  $extension = strtolower(substr(strrchr($filename, '.'), 1)); 
  if($extension == 'html' || $extension == 'htm' || $extension == 'php'){ 
      echo "<a href='".$filename."'><li class='"iso_block"'><span>"**Title Tag Here**"</span></li></a>";
  } 
}

^code from miro(cheers/thanks)

js.Fiddle link for visual: http://jsfiddle.net/AagGZ/547/


Solution

  • $handle = opendir('.');
    $dom    = new DOMDocument();
    
    while (false !== ($file = readdir($handle))){ 
        $extension = strtolower(substr(strrchr($file, '.'), 1));
        if ($extension == 'html' || $extension == 'htm' || $extension == 'php') {
            $title = 'Untitled Document';
    
            if($dom->loadHTMLFile($urlpage)) {
                $list = $dom->getElementsByTagName("title");
                if ($list->length > 0) {
                    $title = $list->item(0)->textContent;
                }
            }
    
            echo "<a href='$filename'><li class='iso_block'><span>$title</span></li></a>";
        } 
    }