PHP: ottenere un elenco di documenti HTML presenti in una directory

In PHP possiamo ottenere un elenco di documenti HTML presenti in una directory.

PHP di Gabriele Romanato

In PHP possiamo ottenere un elenco di documenti HTML presenti in una directory.

Possiamo implementare la seguente funzione.


function get_html_files($dir) {
    $base = $_SERVER['DOCUMENT_ROOT'] . '/' . $dir;
    $files = array_diff(scandir($base), ['..', '.']);
    $output = [];
    foreach($files as $file) {
        if(preg_match('/\.html$/', $file)) {
            $document_path = $base . '/' . $file;
            $doc = new DOMDocument();
            $doc->loadHTMLFile($document_path);
            $title = $doc->getElementsByTagName('title')->item(0)->firstChild->nodeValue;

            $output[] = [
                'title' => $title,
                'path' => $document_path
            ];
        }
    }
    return $output;
}

Commenti