Php content type word

I can download my microsoft word successfully if I named it in the filename by default. But if I use $variables to name it. The document extension will be unknown.

Sample:

$No = 1; 
$Name = 'John'; 
$Test = 'Science';

//Download header
$document->save($doc);
header('Content-Description: File Transfer');
header('Content-Type: application/msword');
header("Content-Disposition: attachment; filename='$No_$Name_$Test.docx");
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($doc));
ob_clean();
flush();
readfile($doc);

So if i rename my filename as variables. The file download will be without the docx extension. Anyone can advise?

Thanks

octern's user avatar

octern

4,79620 silver badges38 bronze badges

asked Jul 14, 2012 at 21:01

JLearner's user avatar

Correct headers are

for Excel (*.xlsx):

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $fileName . '"');

for Word (*.docx):

header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Disposition: attachment;filename="' . $fileName . '"');

answered Mar 29, 2013 at 12:46

Konstantin Smolyanin's user avatar

4

Change this

header('Content-Type: application/msword');

to

header('Content-Type: application/octet-stream');

EDIT:

And change

header("Content-Disposition: attachment; filename='$No_$Name_$Test.docx");

to

header("Content-Disposition: attachment; filename="{$No}_{$Name}_{$Test}.docx"");

answered Jul 14, 2012 at 21:01

5

The correct use of that header is:

Content-Disposition: attachment; filename="fname.ext" note that if the name contains spaces it must be quoted

See RFC6266 section 5. Examples

Community's user avatar

answered Mar 17, 2016 at 3:23

David Valdivieso's user avatar

How to use PHP & Word Using header(”Content-type: application/vnd.ms-word”); The Learn / tutorial php programming how to using  PHP export to Word document ,Word Using header(”Content-type: application/vnd.ms-word”);

ShotDev Focus:
— PHP  & Export to Word document ,Word Using header(”Content-type: application/vnd.ms-word”);.

Example

php_word_header.php

<?
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment; filename=testing.doc");
?>
<html>
<body>
<?
$objConnect = mysql_connect("localhost","root","root") or die(mysql_error());
$objDB = mysql_select_db("mydatabase");
$strSQL = "SELECT * FROM customer";
$objQuery = mysql_query($strSQL) or die ("Error Query [".$strSQL."]");
?>
<table width="600" border="1">
<tr>
<th width="91"> <div align="center">CustomerID </div></th>
<th width="98"> <div align="center">Name </div></th>
<th width="198"> <div align="center">Email </div></th>
<th width="97"> <div align="center">CountryCode </div></th>
<th width="59"> <div align="center">Budget </div></th>
<th width="71"> <div align="center">Used </div></th>
</tr>
<?
while($objResult = mysql_fetch_array($objQuery))
{
?>
<tr>
<td><div align="center"><?=$objResult["CustomerID"];?></div></td>
<td><?=$objResult["Name"];?></td>
<td><?=$objResult["Email"];?></td>
<td><div align="center"><?=$objResult["CountryCode"];?></div></td>
<td align="right"><?=$objResult["Budget"];?></td>
<td align="right"><?=$objResult["Used"];?></td>
</tr>
<?
}
?>
</table>
<?
mysql_close($objConnect);
?>
</body>
</html>

Create a php file and save to path root-path/myphp/

Run
http://localhost/myphp/php_word_header.php

Screenshot

PHP & Word Using header(”Content-type: application/vnd.ms-word”);

PHP & Word Using header(”Content-type: application/vnd.ms-word”);
.
.
.

Download this script.
Download

Category: PHP & Word (Word.Application) by admin

1 Star2 Stars3 Stars4 Stars5 Stars6 Stars7 Stars8 Stars9 Stars10 Stars (1 votes, average: 1.00 out of 10)

Loading ... Loading …

Leave a Reply

You must be logged in to post a comment.

  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog How to Create a Ms Wo…   Post a comment Post a comment   See comments See comments (1)   Trackbacks (0)  

Top featured articles

12. This article

Author: Viewers: 1,919Last month viewers: 475Categories: PHP Tutorials

Many PHP applications need to generate word processing documents in Microsoft Word format so they can be served to the application users in a way that their browser can make it opens in the Microsoft Word program.

Fortunately, nowadays this is very simple. Read this article to learn how to can do it with a few lines of PHP code.

Loaded Article

How to Create a Ms Word Document using PHP in 2019 Very Quickly

Setup the Document HTTP Response Headers

The first thing you need to know is that to make the users’ browsers open file your application serves for download, is that it needs to set the appropriate HTTP headers to specify a content type that usually the browser is configured to open using Microsoft Word.

So, first set the headers Content-type to application/vnd.ms-word and Content-Disposition to make the browser understand that the data being served is a attached for download with a given file name, in the following example it is yourcoolwordfile.doc.

<?php
 header("Content-type: application/vnd.ms-word");
 header("Content-Disposition: attachment; Filename=yourcoolwordfile.doc");
?>

Serve the Document in HTML Format

Then you need to serve the document data like a regular HTML page with the correct meta tags like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Windows-1252">
</head>

Serve the Document like a Regular HTML Page

Then inside the body tags put what you would like to be displayed in the doc file such as:

<body>
<h1>My Word File created with PHP</h1>
<p>This is a text</p>
<p>This is another paragraph.</p>
</body>

Conclusion

Very simple huh? Just tun the code above to see it serving a DOC file that is opened in the Microsoft Word programs in the platforms that have that application available.

You need to be a registered user or login to post a comment

1,608,080 PHP developers registered to the PHP Classes site.
Be One of Us!

Login Immediately with your account on:

Facebook

Facebook

Gmail

Gmail

Hotmail

Hotmail

StackOverflow

StackOverflow

GitHub

GitHub

Yahoo

Yahoo

Comments:

1. Don’t understand this article — ignasi (2019-07-23 03:17)
unuseful… — 0 replies
Read the whole comment and replies

  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog How to Create a Ms Wo…   Post a comment Post a comment   See comments See comments (1)   Trackbacks (0)  

На момент написания данной статьи релиз PHPWord датируется 8 июля 2011 года. Да еще бета версия. Конечно старовата, но с другой стороны, если класс хорошо выполняет поставленную задачу, то почему бы и нет?!

К делу: скачиваем, подключаем обычным инклюдом и вперед.

Создаем экземпляр класса:

$PHPWord = new PHPWord();

Необязательно, но можем добавить, что по-умолчанию используем шрифт Arial размером 14 пунктов.

$PHPWord->setDefaultFontName(‘Arial’);
$PHPWord->setDefaultFontSize(14);

Добавляем новый раздел в документ:

$section = $PHPWord->createSection([array $sectionStyle]);

По-умолчанию этот метод создает страницу A4 книжной ориентации. Поля: по 2,5 см верхнее, левое и правое и 2 см нижнее.

Массив $sectionStyle может содержать:

$sectionStyle = array(
    ‘orientation’ => ‘landscape’, // альбомная ориентация страницы
    ‘marginTop’ => ‘0’, // по-умолчанию равен 1418* и соответствует 2,5 см отступа сверху
    ‘marginLeft’ => ‘0’, // по-умолчанию равен 1418* и соответствует 2,5 см отступа слева
    ‘marginRight’ => ‘0’, // по-умолчанию равен 1418* и соответствует 2,5 см отступа справа
    ‘marginBottom’ => ‘0’, // по-умолчанию равен 1134* и соответствует 2 см отступа снизу
    ‘pageSizeW’ => ‘8419’, // по-умолчанию равен 11906* и соответствует 210 мм по ширине
    ‘pageSizeH’ => ‘11906’, // по-умолчанию равен 16838* и соответствует 297 мм по высоте
    ‘borderColor’=>’999999’, // Цвет ненужного бордюра
    ‘borderSize’=>’100’, // Ширина ненужного бордюра*
);

* В качестве единиц измерения тут используются типографские твипы. Для справки: 1 твип равен 1/567 см.

Текст

У нас есть пустая страница. Для начала добавим обычную текстовую строку. Для этого существует метод addText() и два синтаксиса:

$section->addText(string $text[, array $textStyle]);
// или
$section->addText(string $text[, string $fontStyleName[, string $paragraphStyleName]]);

На практике выглядит это так:

$section->addText(‘Создание сайтов — Лаборатории WEB’);

Тут стоит сделать замечание: автор PHPWord решил, что все, кто будет пользоваться его классом будут работать в кодировке отличной от UTF-8. Если просматривать код PHPWord, то там везде, как через мясорубку, все текстовые переменные проходят через utf8_encode(). Вот в моем случае это сыграло не на руку, потому что я как раз-то работаю с UTF-8.

Что делать, если вы тоже работаете с UTF-8? Варианта как минимум два:

  1. перед тем как отдать строки в PHPWord измените их кодировку на не UTF-8 с помощью iconv();
  2. прошерстите PHPWord и удалите все utf8_encode() оттуда.

Мной был выбран второй вариант.

Двигаемся дальше… Наведем «красоту» в тексте.

Первый вариант — это объявление всякой «красоты» непосредственно в методе addText().

$section->addText(‘Разработка сайтов — Лаборатория WEB’, array(
    ‘name’ => ‘Tahoma’,
    ‘color’ => ‘990000’,
    ‘bold’ => true,
    ‘italic’ => true,
    ‘size’ => 16,
));

Второй вариант — объединение набора «красот» в стиль.

$PHPWord->addFontStyle(‘fStyle’, array(
    ‘name’ => ‘Tahoma’,
    ‘color’ => ‘990000’,
    ‘bold’ => true,
    ‘italic’ => true,
    ‘size’ => 16,
));
$section->addText(‘Изготовление сайтов — Лаборатория WEB’, ‘fStyle’);

Сейчас был задан стиль для шрифта, но можно задать стиль и для параграфа:

$PHPWord->addParagraphStyle(‘pStyle’, array(
    ‘align’ => ‘center’,
    ‘spaceBefore’ => 100, // отступ сверху
    ‘spaceAfter’ => 100, // отступ снизу
    ‘spacing’ => 100, // межстрочный интервал
));

И использовать эти стили как совместно, так и по-отдельности:

$section->addText(‘Поддержка сайтов — Лаборатория WEB’, ‘fStyle’, ‘pStyle’);
// или
$section->addText(‘Продвижение сайтов — Лаборатория WEB’, null, ‘pStyle’);

Если вам нужно объединить в одном параграфе несколько текстовых блоков с разным форматированием, то для этого существует метод createTextRun():

$textrun = $section->createTextRun(‘pStyle’);
$textrun->addText(‘Жирный’, array(
    ‘bold’ => true
));
$textrun->addText(‘Курсив’, array(
    ‘italic’ => true
));
$textrun->addText(‘Красный’, array(
    ‘color’=>’990000’
));

С текстом, вроде, все ясно. Перенос курсора на следующую строку:

$section->addTextBreak([int $number]); // В скобках указывается количество строк на которое нужно перейти. По-умолчанию $number = 1

Изображения

Изображения вставляются также просто, как и текст. Для этого используется метод addImage():

$section->addImage(string $srcLocalImage[, array $imageStyle]);

Массив $imageStyle может содержать:

$imageStyle = array(
    ‘width’ => ‘200’, // в пикселях
    ‘height’ => ‘200’, // в пикселях
    ‘align’ => ‘center’, // left || right || center
)

На практике это выглядит так:

$section->addImage(‘path-to-image.png’, $imageStyle);

Ссылки

Метод для добавления ссылки addLink():

$section->addLink(string $url, [string $text[, string $linkFontStyle[, string $paragraphStyle]]]);

Наведение «красоты» для ссылки:

$PHPWord->addLinkStyle(‘lStyle’, array(
    ‘name’ => ‘Tahoma’,
    ‘color’ => ‘990000’,
    ‘bold’ => true,
    ‘italic’ => true,
    ‘size’ => 16,
));

На практике это выглядит:

$section->addLink(‘http://www.w-lab.ru’, ‘Лаборатория WEB’, ‘lStyle’, ‘pStyle’);

Таблицы

С таблицами немного сложнее. Для добавления таблицы на страницу используем метод addTable(). Как и в случае с текстом, для таблиц существует два синтаксиса. Первый выглядит так:

$table = $section->addTable([array $tableStyle]);

Массив $tableStyle может содержать:

$tableStyle = array(
    ‘cellMarginTop’ => 0, // отступ от ячейки сверху *
    ‘cellMarginRight’ => 0, // отступ от ячейки справа *
    ‘cellMarginBottom’ => 0, // отступ от ячейки снизу *
    ‘cellMarginLeft’ => 0, // отступ от ячейки слева *
);

* в твипах.

cellMarginTop, cellMarginRight, cellMarginBottom, cellMarginLeft можно заменить одним cellMargin.

Второй синтаксис:

$table = $section->addTable([string $tableStyleName]);

Для того, чтобы назначить $tableStyleName, вызовем метод addTableStyle():

$PHPWord->addTableStyle(string $styleName, array $tableStyle[, array $firstRowTableStyle]);

Как можно понять из названия, массив $firstRowTableStyle отвечает за стили первой строки таблицы.

На практике:

$word->addTableStyle(‘tStyle’,  array(
    ‘borderSize’ => 6,
    ‘borderColor’ => ‘999999’,
    ‘cellMarginTop’ => 40,
    ‘cellMarginRight’ => 20,
    ‘cellMarginBottom’ => 40,
    ‘cellMarginLeft’ => 20,
), array(
    ‘borderSize’ => 12,
    ‘borderColor’ => ‘000000’,
    ‘cellMargin’ => 80,
));
$table = $section->addTable(‘tStyle’);

Тут мы назначили для ячеек всей таблицы ширину границы 6, цвет серый, с отступами 40 20 40 20. А для ячеек первой строки ширину границы 12, черного цвета с отступами 80 со всех сторон.

Теперь в таблицу нужно добавить строку. Для этого существует метод addRow():

$table->addRow([int $rowHeight]); // $rowHeight — высота строки в твипах

И методом addCell() добавляем ячейку:

$cell = $table->addCell(int $cellWidth[, array $cellStyle]);

Здесь $cellWidth — ширина ячейки в твипах, а массив $cellStyle может содержать:

$cellStyle = array(
    ‘valign’ => ‘center’, // top || bottom || center || both
    ‘textDirection’ => PHPWord_Style_Cell:TEXT_DIR_BTLR, // PHPWord_Style_Cell:TEXT_DIR_BTLR || PHPWord_Style_Cell:TEXT_DIR_TBRL
    ‘bgColor’ => ‘fafafa’,
    ‘borderTopSize’ => 6,
    ‘borderRightSize’ => 6,
    ‘borderBottomSize’ => 6,
    ‘borderLeftSize’ => 6,
    ‘borderSize’ => 6, // вместо borderTopSize, borderRightSize, borderBottomSize, borderLeftSize
    ‘borderTopColor’ => ‘999999’,
    ‘borderRightColor’ => ‘999999’,
    ‘borderBottomColor’ => ‘999999’,
    ‘borderLeftColor’ => ‘999999’,
    ‘borderColor’ => ‘999999’, // вместо borderTopColor, borderRightColor, borderBottomColor, borderLeftColor
);

Последнее, что нужно сделать — это добавить содержимое в новую ячейку (добавим текст). Сделать это можно двумя способами:

$cell = $table->addCell();
$cell->addText(‘Создание Langing Page — Лаборатория WEB’);
// или
$table->addCell()->addText(‘Разработка Langing Page — Лаборатория WEB’);

Списки

Добавление на страницу нумерованных и ненумерованных списков осуществляется методом addListItem():

$section->addListItem(string $text[, int $depth[, string $textStyle[, array $listStyle[, string $paragraphStyle]]]]);

Здесь $depth — глубина (вложенность) списка от 1 до 9, а массив $listType может состоять из:

$listType = array(
    ‘listType’ => PHPWord_Style_ListItem:TYPE_NUMBER, // одноуровневый нумерованный список
);

Также параметр ‘listType’ может принимать следующие значения:

  • PHPWord_Style_ListItem:TYPE_NUMBER_NESTED — многоуровневый нумерованный список;
  • PHPWord_Style_ListItem:TYPE_BULLET_FILLED — ненумерованный список с маркерами в виде закрашенных кругов;
  • PHPWord_Style_ListItem:TYPE_BULLET_EMPTY — ненумерованный список с маркерами в виде незакрашенных кругов;
  • PHPWord_Style_ListItem:TYPE_SQUARE_FILLED — ненумерованный список с маркерами в виде закрашенных квадратов.

Колонтитулы

При работе с колонтитулами нужно помнить, что они привязываются к разделу и выглядят одинаково на всех страницах, относящихся к одному и тому же разделу.

Создадим верхний и нижний колонтитулы и добавим в них содержимое:

$header = $section->createHeader();
$header->addText(‘Лаборатория WEB’);

$footer = $section->createFooter();
$footer->addPreserveText(‘Страница {PAGE} из {NUMPAGES}’, array(
    ‘italic’ => true,
),
array(
    ‘align’ => ‘right’,
));

Метод addPreserveText() существует специально для добавления номеров страниц.

Разное

$section->addPageBreak(); // Разрыв страницы

Метаданные:

$meta = $PHPWord->getProperties();
$meta->setTitle(‘Название’);
$meta->setSubject(‘Тема’);
$meta->setCreator(‘Автор’);
$meta->setCompany(‘Учреждение’);
$meta->setDescription(‘Заметки’);
$meta->setCategory(‘Группа’);
$meta->setLastModifiedBy(‘Автор изменений’);
$meta->setKeywords(‘Ключевые слова’);
$meta->setCreated(time()); // Дата и время создания документа
$meta->setModified(time()); //Дата и время последнего изменения документа

Сохранение файлов

В файл на жесткий:

$writer = PHPWord_IOFactory::createWriter($PHPWord, ‘Word2007’);
$writer->save(‘document.docx’);

Вывод вопроса на скачивание:

header(«Content-Type: application/msword»);
header(«Content-Transfer-Encoding: binary»);
header(‘Content-Disposition: attachment;filename=»document.docx»‘);
header(‘Cache-Control: max-age=0’);
$writer = PHPWord_IOFactory::createWriter($PHPWord, ‘Word2007’);
$writer->save(‘php://output’);

How to use PHP & Word Using header(”Content-type: application/vnd.ms-word”); The Learn / tutorial php programming how to using  PHP export to Word document ,Word Using header(”Content-type: application/vnd.ms-word”);

ShotDev Focus:
— PHP  & Export to Word document ,Word Using header(”Content-type: application/vnd.ms-word”);.

Example

php_word_header.php

  1. <?  
  2. header(«Content-type: application/vnd.ms-word»);  
  3. header(«Content-Disposition: attachment; filename=testing.doc»);  
  4. ?>  
  5. <html>  
  6. <body>  
  7. <?  
  8. $objConnect = mysql_connect(«localhost»,«root»,«root»or die(mysql_error());  
  9. $objDB = mysql_select_db(«mydatabase»);  
  10. $strSQL = «SELECT * FROM customer»;  
  11. $objQuery = mysql_query($strSQLor die («Error Query [«.$strSQL.«]»);  
  12. ?>  
  13. <table width=«600» border=«1»>  
  14. <tr>  
  15. <th width=«91»> <div align=«center»>CustomerID </div></th>  
  16. <th width=«98»> <div align=«center»>Name </div></th>  
  17. <th width=«198»> <div align=«center»>Email </div></th>  
  18. <th width=«97»> <div align=«center»>CountryCode </div></th>  
  19. <th width=«59»> <div align=«center»>Budget </div></th>  
  20. <th width=«71»> <div align=«center»>Used </div></th>  
  21. </tr>  
  22. <?  
  23. while($objResult = mysql_fetch_array($objQuery))  
  24. {  
  25. ?>  
  26. <tr>  
  27. <td><div align=«center»><?=$objResult[«CustomerID»];?></div></td>  
  28. <td><?=$objResult[«Name»];?></td>  
  29. <td><?=$objResult[«Email»];?></td>  
  30. <td><div align=«center»><?=$objResult[«CountryCode»];?></div></td>  
  31. <td align=«right»><?=$objResult[«Budget»];?></td>  
  32. <td align=«right»><?=$objResult[«Used»];?></td>  
  33. </tr>  
  34. <?  
  35. }  
  36. ?>  
  37. </table>  
  38. <?  
  39. mysql_close($objConnect);  
  40. ?>  
  41. </body>  
  42. </html>  

Create a php file and save to path root-path/myphp/

Screenshot

PHP & Word Using header(”Content-type: application/vnd.ms-word”);

PHP & Word Using header(”Content-type: application/vnd.ms-word”);
.
.

Понравилась статья? Поделить с друзьями:
  • Php application vnd ms excel
  • Php and word document
  • Php and microsoft excel
  • Php and excel spreadsheet
  • Php and excel files