Подтвердить что ты не робот

Автоматическая загрузка файла с помощью PHPWord

Я пытаюсь использовать PHPWord для создания текстовых документов. И документ может быть сгенерирован успешно. Но есть проблема, когда мой сгенерированный документ будет сохранен на сервере. Как я могу сделать его доступным для загрузки сразу?

Пример:

$PHPWord = new PHPWord();
//Searching for values to replace
$document = $PHPWord->loadTemplate('doc/Temp1.docx');
$document->setValue('Name', $Name);
$document->setValue('No', $No);
$document->save('php://output'); //it auto save into my 'doc' directory.

Как я могу ссылаться на заголовок, чтобы загрузить его следующим образом:

header("Content-Disposition: attachment; filename='php://output'"); //not sure how to link this filename to the php://output..

Просьба сообщить.

4b9b3361

Ответ 1

php://output - это поток только для записи, который записывается на ваш экран (например, echo).

Итак, $document->save('php://output'); не сохранит файл нигде на сервере, он просто повторит его.

Кажется, $document->save, не поддерживает обтекатели потоков, поэтому он буквально сделал файл с именем "php://output". Попробуйте использовать другое имя файла (я предлагаю временный файл, поскольку вы просто хотите его повторить).

$temp_file = tempnam(sys_get_temp_dir(), 'PHPWord');
$document->save($temp_file);

В header поле filename - это то, что PHP сообщает браузеру, что файл назван, это не должно быть имя файла на сервере. Это просто имя, которое браузер сохранит как.

header("Content-Disposition: attachment; filename='myFile.docx'");

Итак, все вместе:

$PHPWord = new PHPWord();
//Searching for values to replace
$document = $PHPWord->loadTemplate('doc/Temp1.docx');
$document->setValue('Name', $Name);
$document->setValue('No', $No);
// // save as a random file in temp file
$temp_file = tempnam(sys_get_temp_dir(), 'PHPWord');
$document->save($temp_file);

// Your browser will name the file "myFile.docx"
// regardless of what it named on the server 
header("Content-Disposition: attachment; filename='myFile.docx'");
readfile($temp_file); // or echo file_get_contents($temp_file);
unlink($temp_file);  // remove temp file

Ответ 2

$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');

$filename = 'MyFile.docx';

$objWriter->save($filename);

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
flush();
readfile($filename);
unlink($filename); // deletes the temporary file
exit;

Ответ 3

// Save File
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
header("Content-Disposition: attachment; filename='myFile.docx'");
$objWriter->save("php://output");

Ответ 4

теперь вместо версии 0.13.0 https://github.com/PHPOffice/PHPWord

<?
require_once "../include/PHPWord-develop/bootstrap.php";

$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('template.docx');

$templateProcessor->setValue('var01', 'Sun');
$templateProcessor->setValue('var02', 'Mercury');

//#####################################################
// Save File
//#####################################################
//#####################################################
header("Content-Disposition: attachment; filename='output01.docx'");
  $templateProcessor->saveAs('php://output');
//#####################################################
//#####################################################
?>

Ответ 5

Это работа для меня:

$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007', $download = true);

header("Content-Disposition: attachment; filename='File.docx'");

$objWriter->save("php://output");

Ответ 6

Извините, что пришел позже. Я наткнулся на это, пытаясь решить ту же проблему. Мне удалось заставить его работать на Laravel 5, используя ниже:

    $file_dir = $template_upload_dir.DIRECTORY_SEPARATOR.'filename.docx';
    $tags = array();
    if (file_exists($file_dir)) {
        $templateProcessor = new TemplateProcessor($file_dir);
        $tags = $templateProcessor->getVariables();
        $replace = array(''); 

        $templateProcessor->setValue($tags, $replace);
        $save_file_name = $fullname.'-'.$inv_code.'-'.date('YmdHis').'.docx';
        $templateProcessor->saveAs($save_file_name);

        return response()->download($save_file_name)->deleteFileAfterSend(true);
    }

Надеюсь, это поможет кому-то!!!

Ответ 7

Простое решение для Laravel, основанное на ответе @user3214824.

// ...    
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($PHPWord, 'Word2007');
$doc_name = 'fileName.docx';
$objWriter->save($doc_name); // saving in the public path just for testing

return response()->download(public_path($doc_name))->deleteFileAfterSend(true);