Andryushkin.ru
Блог им. alex-borisi (Александра Андрюшкина)

Doc2Txt — исправлен для php 8

Подправил класс для чтения doc / docx документов

Файл doc2txt.class.php

class Doc2Txt 
{
	private $filename;
	
	public function __construct($filePath) {
		$this->filename = $filePath;
	}
	
	private function read_doc()	{
		$fileHandle = fopen($this->filename, "r");
		$line = @fread($fileHandle, filesize($this->filename));   
		$lines = explode(chr(0x0D),$line);
		$outtext = "";
		foreach($lines as $thisline)
		  {
			$pos = strpos($thisline, chr(0x00));
			if (($pos !== FALSE)||(strlen($thisline)==0))
			  {
			  } else {
				$outtext .= $thisline." ";
			  }
		  }
		 $outtext = preg_replace("/[^a-zA-Z0-9\s\,\.\-\n\r\t@\/\_\(\)]/","",$outtext);
		return $outtext;
	}

	private function read_docx() 
	{
		$zip = new ZipArchive;

	    // Открываем файл DOCX
	    if ($zip->open($this->filename) === TRUE) {
	        // Проверяем, существует ли файл document.xml в архиве
	        if ($zip->locateName('word/document.xml') !== false) {
	            // Получаем содержимое document.xml
	            $xmlContent = $zip->getFromName('word/document.xml');

	            // Закрываем архив
	            $zip->close();
	            
	            $content = $xmlContent;
	            
				$content = str_replace('</w:r></w:p></w:tc><w:tc>', " ", $content);
				$content = str_replace('</w:r></w:p>', "<hr>\r\n", $content);
				$striped_content = strip_tags($content,'<br>,<hr>');

				$explode = explode('<hr>', $striped_content);
				foreach($explode AS $key => $value) {
					$text = trim($value); 

					if (empty($text)) {
						unset($explode[$key]);
						continue;
					}

					$explode[$key] = '<p>' . $text . '</p>';
				}

				return join("\r\n", $explode);
	        } else {
	            $zip->close();
	            return "document.xml не найден в файле.";
	        }
	    } else {
	        return "Не удалось открыть файл.";
	    }
	}

	public function convertToText() {
	
		if(isset($this->filename) && !file_exists($this->filename)) {
			return "File Not exists";
		}
		
		$fileArray = pathinfo($this->filename);
		$file_ext  = $fileArray['extension'];
		if($file_ext == "doc" || $file_ext == "docx")
		{
			if($file_ext == "doc") {
				return $this->read_doc();
			} else {
				return $this->read_docx();
			}
		} else {
			return "Invalid File Type";
		}
	}
}

Пример

require_once 'doc2txt.class.php';

$file = 'filename.docx'; 

$reader = new Doc2Txt($file); 
echo $reader->convertToText(); 

Просмотров: 921