Разберите файлы txt и превратите их в статические html-файлы

ОБНОВЛЕНИЕ (11/24/2015)

У меня все работает правильно, кроме одной небольшой детали. Мне нужно выяснить, как получить статические переменные-заполнители, которые у меня есть, в моем шаблоне HTML, чтобы я мог заменить их содержимым, вытащенным из файла TXT.

Вот мой код шаблона:

<!DOCTYPE html> <html> <head> <title>{PAGE_TITLE}</title> </head> <body> {PAGE_TITLE} - {PAGE_AUTHOR} - {PAGE_DATE} {PAGE_CONTENT} </body> </html> 

ОРИГИНАЛ

Я рассмотрел этот вопрос PHP – разбор txt-файла и получил как можно дальше сам.

Я создаю простой, очень маленький статический генератор сайтов в PHP для образовательных целей. У меня есть каталог с одним файлом PHP, в котором весь код будет (за исключением HTML-шаблона), и он будет сканировать текущий каталог для любых файлов txt и решить, есть ли более одного, поэтому цикл можно использовать для обрабатывать каждый файл.

Мой txt-файл структурирован так:

 TITLE AUTHOR DATE Text starts here... 

Я застрял на части, где я вытаскиваю TITLE, AUTHOR, DATE и текстовое содержимое из файла и сохраняю их в своих правильных переменных, чтобы информация могла быть передана HTML-шаблону, который будет обработан.

Я также хотел бы, чтобы он был настроен так, когда есть новая строка / return, он добавит тег абзаца HTML к этому блоку текста.

Вот код, который я имею до сих пор для файла PHP:

 <?php $files = glob("*.txt"); // Scan directory for .txt files // Check that there are .txt files in directory if ($files !== false) { $numberOfFiles = count($files); // Count number of .txt files in directory // Check if number of files is greater than one if ($numberOfFiles > 1) { // Advanced loop will go here to process multiple txt files } else { $file_handle = fopen ($files[0], "r"); // Open file // Loop through file contents line-by-line while (!feof ($file_handle)) { $file = file_get_contents($files[0]); // Get file contents $rows = explode ("\n", $file); // Count number of rows in file // Need to pull TITLE, AUTHOR, and DATE from txt file // Here's where I need the rest of the file's content to be parsed into paragraph blocks for the html template break; // Break loop after one run } fclose ($file_handle); // Close file connection } } ?> 

Вы можете получить строки из файла один за другим, вместо того, чтобы получать весь файл, а затем форматировать их по отдельности и помещать их в переменные, готовые для эха на вашей странице. Тем не менее, метод, предложенный Dontfeedthecode, настолько превосходен и эффективнее, что я снял оригинал и надеюсь, что он одобрит то, что я сделал с его идеей.

  <?php $files = glob("*.txt"); // Scan directory for .txt files // Check that there are .txt files in directory if ($files !== false) { $numberOfFiles = count($files); // Count number of .txt files in directory // Check if number of files is greater than one if ($numberOfFiles > 1) { // Advanced loop will go here to process multiple txt files } else { $text_array = array(); $file_handle = fopen ($files[0], "r"); // Open file $text_array = stream_get_contents($file_handle); $text_array = explode("\n", $text_array); // get the top three lines $page_title = trim($text_array[0]); $all_lines = '<p>' . trim($text_array[0]) . ' - ' . trim($text_array[1]) . ' - ' . trim($text_array[2]) . '</p>'; // delete the top four array elements $text_array[0] = $text_array[1] = $text_array[2] = $text_array[3] = ''; // get the remaining text $text_block = trim(implode($text_array)); fclose ($file_handle); // Close file connection } // endifs for first if(... statements } ?> 

Выход HTML:

  <!DOCTYPE html> <html> <head> <title><?php echo $page_title; ?></title> </head> <body> <?php echo $all_lines . "\n" . '<p>' . $text_block .'</p>'. "\n"; ?> </body> </html> A variable ready to print to file: <?php $print_to_file = '<!DOCTYPE html> <html> <head> <title>' . $page_title . '</title> </head> <body>' . "\n" . $all_lines . "\n" . '<p>' . $text_block .'</p>'. "\n" . ' </body> </html>'; echo $print_to_file; ?> 

HTML выглядит немного смещенным в переменной здесь, но выходит правильно при печати.

И, наконец, версия, которая помещает <p> для каждой строки текста.

  <?php $files = glob("*.txt"); // Scan directory for .txt files // Check that there are .txt files in directory if ($files !== false) { $numberOfFiles = count($files); // Count number of .txt files in directory // Check if number of files is greater than one if ($numberOfFiles > 1) { // Advanced loop will go here to process multiple txt files } else { $text_array = array(); $file_handle = fopen ($files[0], "r"); // Open file $text = stream_get_contents($file_handle); // get the top three lines $text_array = explode("\n", $text); $page_title = trim($text_array[0]); $all_lines = '<p>' . $text_array[0] . ' - ' . $text_array[1] . ' - ' . $text_array[2] . '</p>'; // set up something to split the lines by and add the <p> tags $text_array = str_replace("\n","</p>\nxxx<p>", $text); $text_array = explode("xxx", $text_array); // delete the top four array elements $text_array[0] = $text_array[1] = $text_array[2] = $text_array[3] = ''; // get the remaining text $text_block = trim(implode($text_array)); } } ?> 

Эта версия может использовать те же блоки html / php, что и выше