2015-11-22 2 views
3

UPDATE (11/24/2015)Анализировать текстовые файлы и превратить их в статические HTML файлы

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

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

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

ORIGINAL

Я рассмотрел этот вопрос PHP - parsing a txt file и получил, насколько я мог самостоятельно.

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

Мой TXT файл структурированы следующим образом:

TITLE 
AUTHOR 
DATE 

Text starts here... 

Я застрял на той части, где я тянуть название, автор, дата и содержание текста из файла и сохранять их в правильных переменных так эта информация может быть передана 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 
    } 
} 
?> 
+2

Если название, автор и дата всегда на первых трех строках вы можете вытащить их с $ строки [0], $ строки [ 1] и $ rows [2]. Чтобы получить текст, вы можете удалить эти первые три элемента из массива и развязать его обратно вместе, заключенные в теги абзаца. –

+1

Возможно, файл csv-типа с одной строкой на элемент может быть проще управлять, чем несколько отдельных файлов? – Steve

+1

Метод Dontfeedthecode выглядит неплохим и эффективным способом сделать это. – Steve

ответ

3

Вы можете получить строки из файла по одному, вместо того, чтобы весь файл, а затем их по отдельности форматирование и положить их в переменные, готовые для эха на вашей странице. Тем не менее, метод, предложенный 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 блоки, как описано выше

Смежные вопросы