Skip to content

Instantly share code, notes, and snippets.

@appbak3r
Last active August 29, 2015 14:10
Show Gist options
  • Save appbak3r/e741bec6db04b22ddddd to your computer and use it in GitHub Desktop.
Save appbak3r/e741bec6db04b22ddddd to your computer and use it in GitHub Desktop.
Create docx file with variables escaped with {variable}
<?php
/**
* Класс для генрации Docx
* User: Алексей Дмитриев
* Date: 10.07.14
* Time: 17:52
*/
class FileConverterDOC extends FileConverter {
private $tmpFilePath;
public function __construct($filename) {
$id = session_id();
$this->tmpFilePath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid() . $id . '.docx';
if (!copy($filename, $this->tmpFilePath)) {
throw new Exception('Не удалось скопировать файл!');
}
$ZipArchive = new ZipArchive();
$ZipArchive->open($this->tmpFilePath);
$this->html = $ZipArchive->getFromName('word/document.xml');
$ZipArchive->close();
}
/**
* Метод сохраняет сгенерированный файл в путь $outputName
*
* @param $outputName string Путь до нового файла
* @param $download bool Force Download
* @return mixed
*/
public function save($outputName, $download = false) {
$ZipArchive = new ZipArchive();
$ZipArchive->open($this->tmpFilePath);
$ZipArchive->addFromString("word/document.xml", $this->html);
$ZipArchive->close();
header('Content-Description: File Transfer');
header("Content-Type: application/zip");
header("Content-disposition: attachment; filename=\"$outputName .docx\"");
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' .filesize($this->tmpFilePath) );
readfile($this->tmpFilePath);
}
}
/**
* Класс для работы с конвертацией файлов
* User: Алексей Дмитриев
* Date: 4/24/14
* Time: 4:05 PM
*/
abstract class FileConverter
{
/**
* @var string HTML код
*/
public $html;
/**
* Присваивает внутренней переменной $html -> строку $htmlString
*
* @param $htmlString string HTML-код для конвертации
*/
public function __construct($htmlString) {
$this->html = $htmlString;
}
/**
* Метод сохраняет произведенный файл в путь $outputName
*
* @param $outputName string Путь до нового файла
* @param $download bool Force Download
* @return mixed
*/
abstract public function save($outputName, $download = false);
/**
* Метод заменяет в HTML строки соответствующие ключам массива на значения массива
*
* @param array $array
* @param string $escape_char
* @return mixed
*/
public function replace(array $array, $escape_char = '{}'){
foreach ($array as $key=>$val){
$this->html = str_replace($escape_char[0].$key.$escape_char[1],$val, $this->html);
}
$this->html = preg_replace('/'.$escape_char[0].'.*'.$escape_char[1] .'/','', $this->html);
}
}
//Usage
$path_to_template = '/home/alex/my_template.docx';
$document = new FileConverterDOC($path_to_template);
$arFields = array('key1'=>'value1');
$document->replace($arFields);
$document->save('output.docx', true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment