Перевод php в word

Конвертировать PHP to Word онлайн

Loading…

Обработка Пожалуйста, подождите…

Копировать текст

copy link

Копировать ссылку

copy link


send to email

Обработка Пожалуйста, подождите…

Файл отправлен на

clear email

Ваше мнение важно для нас, пожалуйста, оцените это приложение.





Спасибо за оценку нашего приложения!

PHP to Word conversion

Conholdate PHP to Word Conversion — это кроссплатформенное и кроссбраузерное приложение для конвертации, которое позволяет конвертировать PHP to Word в любом современном браузере (Chrome, Safari, Firefox, Opera, Tor и т. д.) и на любой ОС (Windows, Unix и MacOS), независимо от характеристик вашего ПК. Преобразованный PHP to Word сохранит исходную структуру, содержимое и стили документа. PHP to Word Приложение для конвертирования построено на основе высококачественного механизма преобразования документов, который обеспечивает выдающиеся результаты преобразования и производительность. Наша цель — предложить нашим пользователям безопасные и наилучшие возможности преобразования. Приложение Conholdate.Conversion предлагает функцию OCR, которая позволяет анализировать файлы изображений и экспортировать данные в документы Excel, например преобразовывать PNG в Excel.

Как Конвертировать PHP to Word

  1. Щелкните внутри области перетаскивания или перетащите файл.
  2. Подождите, пока файл PHP to Word не будет загружен.
  3. Выберите выходной формат из выпадающего меню.
  4. Нажмите кнопку Конвертировать, чтобы начать преобразование PHP to Word.
  5. Скачайте или поделитесь полученным файлом.

How to

часто задаваемые вопросы

Q: Как преобразовать файл PHP to Word?

A: Загрузите файл, перетащив его в зону загрузки или щелкните по нему, чтобы выбрать файл с помощью проводника. После этого выберите конечный формат, в который вы хотите преобразовать файл, и нажмите кнопку Преобразовать.

Q: Могу ли я извлечь таблицы из изображений (PNG) и экспортировать их в файлы Excel?

A: Да, это возможно. Преобразование Conholdate изображения в Excel будет анализировать файлы изображений с помощью функции OCR и извлекать текст и данные таблиц. Извлеченные данные можно сохранить в различных форматах, таких как Excel, OpenOffice и других.

Q: Сколько файлов можно конвертировать одновременно?

A: Вы можете конвертировать по 1 файлу за раз.

Q: Каков максимально допустимый размер файла?

A: Максимально допустимый размер файла для загрузки и конвертации составляет 20 МБ.

Q: Как получить результаты конвертирования файла?

A: В конце процесса преобразования вы получите ссылку для скачивания. Вы можете скачать результаты сразу или отправить ссылку на вашу электронную почту.

Q: Как многостраничный документ преобразуется в изображение?

A: Каждая страница такого документа будет сохранена как отдельное изображение. После завершения конвертации вы получите набор таких изображений.

Еще приложений

Еще conversion приложений

Выбрать язык

HTML to Word

The conversion of HTML into Word is one of the most requested functionalities of phpdocx. PHP was born as a server tool for the generation of dynamical HTML pages, so it is no wonder that many of our phpdocx users are pretty familiar with that type of task and they want to take advantage of those skills for the generation of Word documents.

phpdocx offers pretty sophisticated ways to include HTML formatted content into a Word document. The purpose of this tutorial is to offer a detailed account on how one can do it and how to get the most of it.

There are currently two methods to include HTML into a Word document generated from scratch (the case of templates will be treated further below) with phpdocx:

  • addExternalFile()
  • embedHTML()

The first one uses internally the «alternative content» element available in the OOXML standard (on which Word is based) and it is simple to use although it has two main drawbacks:

  • It is not compatible with LibreOffice, OpenOffice and some DOCX readers
  • There is not much flexibility in the rendering options

That said, it may be an interesting option if none of the above represents an issue for a given application.

In what follows we will concentrate in the embedHTML method and the replaceVariableByHTML (its avatar for working with Word templates).

The main advantages of the embedHTML methods are summarised in:

  • The HTML code is translated into native WordML code so the resulting document may be rendered with all DOCX readers and transformed to PDF with the help of the phpdocx conversion plugin (included in the Advanced and Premium versions of the library).
  • One may use native Word styles for paragraphs and tables.
  • One may filter the HTML content by ids, CSS classes and HTML tags or even by simple XPath expressions.
  • One may add the images included in the HTML code within the Word document or as external resources.
  • Headings may get included into a Table of Contents.
  • It allows the direct insertion of HTML+CSS code or the embedding and preprocessing of an external web page.
  • The resulting WordML may be also inserted in headers and footers and other contents.

And once again with a single line of PHP code.

To get the best DOCX output these methods provide, please install and enable PHP Tidy and PHP mbstring extensions on your server.

Let us first offer a few simple examples that illustrate the most elementary procedures:

Simple HTML code

The code needed to insert some plain HTML is as simple as this:


And you will get as a result (download the corresponding document):

Let us first offer a few simple examples that illustrate the most elementary procedures:


And you will get as a result (download the corresponding document):

External HTML source

Sometimes one may need to get the HTML and CSS from existing external files but as we will now show this also turns to be extremely simple.

Let us assume that the HTML code above proceeds from an external HTML page: simpleHTML.html that links to a CSS stylesheet: styles.css.

Then the following code will render exactly the same results:

Notice that the only differences are:

  • The $html variable is now the path to an external HTML page.
  • The option isFile is set to true to indicate phpdocx that the variable $html is a path rather than HTML code.

HTML code embedded within a Word table

It may well be that you choose not to embed directly the HTML code into the document but rather insert it within another document element like a table or a header/footer.

This can be achieved in a very simple way using the WordFragment class.

You may modify slightly the previous example:


Obtaining now the following result (download the corresponding Word document):

Embedding images

To include images is equally simple. One may choose to include the images within the document (with the option downloadImages set to true) or keep them as an externally linked resource (in that case you should make sure that the image is available to the final users).

A simple example that makes use of this simple web page with an image reads as follows:


The resulting Word document looks as follows (download the corresponding document):

Notice that, as in this case you have not declared the width and height attributes of the image, phpdocx reads its properties from the image header and inserts it with a resolution of 96 dpi (default resolution). One may, of course, choose custom width and height to obtain the desired results.


Supported HTML tags and attributes

phpdocx parses all the most commonly used HTML tags and attributes.

It is important to take into account that the HTML and OOXML that Word is based on have different goals so at some points the translation from one to the other should include certain compromises that are not universally valid for all applications. Fortunately it is not difficult to find convenient workarounds that offer a close to perfect Word rendering.

The list of currently parsed HTML elements include:

Block type HTML elements

  • div: Although this tag is probably the most frequent in modern HTML code, it does not have a direct translation into Word. phpdocx offers different parsing options:

    • Only use it for the CSS inheritance and parse consequently its child elements.
    • Parse them as a «p» element with the option «parseDivs» set to «paragraph» (this may be an useful option when using HTML code coming from a WYSIWYG editor).
    • Parse it as a table with the option «parseDivs» set to «table». This may be the most accurate option if one may decide to preserve all available formatting but may produce complicated Word documents that may be later difficult to edit manually (if that is an interesting option).
  • p: This is, of course, a native Word element so it is parsed as expected.
  • h1, h2, h3, h4, h5 and h6: They are parsed as Word headings and as such they may show up in a TOC included in the Word document.
  • ul and ol: Are respectively parsed as unordered or ordered Word lists.
  • li: Are parsed like individual list items belonging to a predefined ordered or unordered list.
  • dl, dt, dd: Are treated like definition lists in standard HTML.
  • table: They are parsed as Word tables and the following attributes are taken into account: border, align and cellspacing. All its children are consequently parsed: thead, tbody, tr, th and td and its corresponding colspan and rowspan attributes.
  • img: Images are converted into Word images and they can be integrated in the Word document by setting the option «downloadImages» to true or, if prefered, be kept like an external resource (this option could be particularly interesting if you expect the image to change with time), this requires an open Internet connection whenever the Word document is visualised. Besides the src attribute the width and height are also parsed. All other styling options should be defined via CSS properties. figcaption tag is also supported.
  • br and hr: They include, respectively, a line break and an horizontal ruler in the Word document.

Inline type HTML elements

  • a: Are parsed as external links, internal links or bookmarks (with the parseAnchors set to true in the last two cases) depending on the value of the href or name attribute.
  • strong, b, i, em, u, span, sup, sub, blockquote, address, center, listing, plaintext, xmp, pre, cite, var, dfn, tt, code, kbd, ins, s, strike, del, big, small: Are parsed as text with their corresponding default properties unless they are overwritten by explicit CSS style properties.

HTML web form elements

  • input: Inputs are parsed depending on their type attribute:

    • text: Is converted into a Word text field. The size attribute determines the corresponding length in the Word field.
    • checkbox and radio: In both cases they are converted into Word checkboxes. The checked is parsed and activates the checked elements in the Word document.
  • select and option: They transform into the corresponding Word dropdown field element with their corresponding options. Once again if there is a selected option in the HTML code it appears selected by default in the Word document.

    WARNING:

  • When a tag is not parsed, it does not mean that its content disappears from the Word document. It only implies that their associated HTML properties are not taken directly into account. Their children and text content will be parsed and rendered with their corresponding styles into the Word document.

Currently almost all CSS properties that are applicable to a document, are parsed and translated into their Word counterparts.

In order to achieve the best possible results it is important to know how these CSS properties are applied and their known limitations regarding the final document rendering.

The list of currently parsed CSS styles include:

Border styles and background color

The following border properties are parsed:

  • border: One may introduce combined properties as, for example, «1px solid red». Some comments about units and format:

    • Units: One may use pixels, points or ems.
    • Styles: The available styles are: None, dotted, dashed, solid, double, groove, inset, outset.
    • Colors: One can enter hexadecimal values like #ff0000 or, if it exists, standard CSS colors like «red» (see standard CSS color names list).
  • border-[top, right, bottom, left]: Same as above but letting you choose different borders styles for top, right, bottom and left borders.
  • border-[top, right, bottom, left]-color: Sets up independently the color for each border.
  • border-[top, right, bottom, left]-style: Sets up independently the style (solid, dotted…) for each border.
  • border-[top, right, bottom, left]-width: Sets up independently the size (in pixels, points or ems) for each border.
  • border-collapse: Allows to collapse or separate.
  • background-color: Hexadecimal or standard CSS value.

Margins and paddings

The concept of padding has not a general direct counterpart in Word so it is usually interpreted as extra margin space.

  • margin and padding: One may use pixels, points or ems.
  • margin-[top, right, bottom, left] and padding-[top, right, bottom, left]: Same as above but letting you choose different margins and paddings for top, right, bottom and left.

Page break properties

This properties are partially supported:

  • page-break-after: If set to avoid is equivalent to the Word property of «Keep with next paragraph».
  • page-break-inside: If set to avoid is equivalent to the Word property of «Keep lines together».
  • page-break-before: If set to always is equivalent to the Word property of «Break page before». If it is set to avoid turns on Word widow/orphan control.

Font and text properties

The units may be pixels, points or ems and the colors follow the same scheme as above. The suported properties include:

  • font: If one uses the shorthand properties one need to preserve the following order: font: font-style font-variant font-weight font-size/line-height font-family.
  • font-family: Make sure to include a font family that may be supported by the Word interface (practically all the usual ones). The default value is «serif».
  • font-size: The default size is 12pt.
  • font-style: May be normal, italic or oblique.
  • font-variant: May be normal or small-caps.
  • font-weight: Only recognise bold or bolder that are converted into bold in Word.
  • line-height: May be set in any of the available units.
  • color: Hexadecimal value or standard CSS values.
  • text-decoration: May be underline or line-through.
  • text-align: The available values are left, center, right or justify.
  • text-indent: May be set in any of the available units.
  • text-transform: May be set to uppercase.

Positioning

phpdocx tries to adapt as best as possible the positioning properties of elements to equivalent Word properties. If you need to position precisely elements in the resulting Word document the best and simplest way is to do it with tables.

You may also instruct phpdocx to parse divs as tables (see, for example, above) or to parse floats with the «parseFloats» set to true (image floats are always parsed by default).

In any case results are usually pretty good and cover all but the most sophisticated examples.

The parsed properties include:

  • float: Can be none, left or right.
  • vertical-align: Can be given in pixels, points or ems or like super, sub, top, text-top, middle, baseline, bottom and text-bottom.

Lists

phpdocx handles pretty well the rendering of HTML lists and their associated CSS styles. Nevertheless, if you want to use bullets beyond the most standard ones you should call the phpdocx embedding HTML methods in conjunction with the createListStyle method (by setting the ‘customListStyles’ option to true) to obtain the desired results.

In order to do so one should create a custom style that mimics the HTML result and give it the same name that is given in the HTML code for the corresponding class or id attribute. phpdocx will automatically choose the corresponding formatting (bullets, indents, etcetera) previously defined.

The following code illustrates how to create a lower letter and roman style list style and use it with HTML:

In any case results are usually pretty good and cover all but the most sophisticated examples.

In case that one does not bother to define any custom list style, the corresponding CSS list style property is parsed as follows:

  • list-style and list-style-type: When any of them is set to none no bullets or numbering is included and the CSS properties on margin and padding are used, for all other lists types the standard Word defaults are used.

HTML Extended, available in Premium licenses, include additional options to generate lists with different styles on its levels.

The following example creates a custom list styles with two different styles for the same level, applied to an HTML:


Using native Word formatting with HTML

One of the nicest features of the embedHTML method is that it allows to apply customized Word formatting for paragraphs and tables.

One may write plain HTML with little or none styling and yet generate a very sophisticated Word document.

The default base template already includes all standard Word styles for headings, paragraphs and tables. You may get all the available styles via the phpdocx parseStyles method.

Of course, you may choose a different base template that better suits your needs or even explicitely import styles from other DOCX via the phpdocx importStyles method.

Let us now go over a simple example that illustrate this functionality:

Notice that we have set the option strictWordStyles to true so the HTML parser will ignore the CSS properties and will apply exclusively the selected Word styles.


The resulting Word document looks as follows:

If one removes the option strictWordStyles or set it to false (its default value), phpdocx will try to combine the Word and HTML styles.


The resulting Word document reads (download the corresponding Word document):

phpdocx adds some default styles when the strictWordStyles option is set as false. The addDefaultStyles option prevents adding these default styles.

Another useful functionality of the embedHTML method is the possibility to filter the HTML content included in the Word document.

One may want to reuse HTML code that has been generated with a different goal in your Word document. A typical example is given by the contents of an existing web page from which you just want to extract its contents without menus or navigation that does not really fit into a Word document.

The filtering can be done in two different ways, which are:

Basic expressions

One can select a set of HTML elements by tag, id or class (’’, ‘#myId’ or ‘.myClass’) in a very simple way as follows:


The resulting Word document reads (download the corresponding Word document):

Using XPath expressions

One may choose to filter by more complex expressions that should take the form of valid PHP XPath expressions.

For example, if in the previous example we would have set up the filter option to: //p[@class=»heading2″]|//ul|//table we would have obtained instead a Word document that will only include the paragraph with class heading2, the unordered list and the table.


We obtain this time (download the corresponding Word document):

Besides all the options that have been carefully analysed before, there are are other general options that we now pass to comment briefly.

  • ‘parseAnchors’ (boolean): If set to true it will parse the anchors included in the HTML file. Its default value is false.
  • ‘parseDivs’ (paragraph, table): Although all CSS properties of div tags are inherited divs themselves are not parsed by default because there is no WordML element that exactly resemble its properties. When set to paragraph the phpdocx parser tries to parse them as standard paragraphs (this may be a useful option for HTML coming from certain WYSIWYG editors). If set to table, it renders the div as a Word table. Its default value is false.
  • ‘parseFloats’ (boolean): When set to true phpdocx tries to parse the floating divs and paragraphs as floating tables. Sometimes the results are impredictable, so use with care. Its default values is false.
  • ‘baseURL’ (boolean): Forces the base URL of the relative links to the desired value. This option may be particularly useful if the HTML code is obtained via the PHP file_get_contents method or any similar procedure.

phpdocx includes a base CSS that applies to all HTML contents set to be converted. Those default styles can be overwritten with the styles added in the HTML or with a modification of the template/html.css file, available in every package.


Inserting HTML into Word templates

All the preceding examples have their match in the case we are working with templates by means of the replaceVariableByHtml method.

All the available options are the same as before although we have to give two extra pieces of extra info, namely:

  • The name of the variable we wish to substitute.
  • The type of substitution, with two possible options:

    • block: The whole paragraph containing the variable is replaced by the corresponding HTML.
    • inline: Only the variable itself is replaced by the ‘inline’ HTML content (block elements are removed from the code).
    • inline-block: Replace the variable keeping block contents and placeholder styles. Only available in Premium licenses.

A short example will illustrate it better.


Let us start with a simple template that looks like this:

The following code:


Fields (download the corresponding Word document):


HTML Extended and CSS Extended

Premium licenses include HTML Extended and CSS Extended modes to invoke phpdocx methods with custom HTML tags and apply custom styles not supported by standard HTML tags and CSS styles.

Thus, it is possible to insert headers, footers, comments, table of contents, cross-references, sections and many other contents and styles. All of it integrated with the supported HTML tags and CSS styles.

HTML Extended and CSS Extended have an extra set of methods and options designed to make conversions more flexible and efficient:

  • addBaseCSS: defines a base CSS for all HTML conversions.
  • stylesReplacementType: available for the replaceVariableByHTML method, it allows using the original placeholder styles (pPr y rPr) instead of the ones defined by the imported HTML and CSS, and mix HTML and placeholder styles.
  • embedFonts: embeds TTF fonts from @font-face rules.
  • support overwriting styles in level lists: create lists with different styles in the same levels.
  • extraHTMLExtendedOptions: transform additional contents just like tabs.

An easy example of use of HTML Extended would be the creation of a header and footer:

Or adding contents by mixing HTML and HTML Extended:

HTML Extended also allows to customize the tags you are working with. E.g., to use header instead of the default phpdocx_header. All the documentation regarding this feature is available on the HTML Extended page.

Первое с чего нужно начать, это создать .docx документ на своем ПК, например template.docx

Для примера я взял куски из договора на создание сайта

Подготавливаем шаблон word документа

Открываем word файл и начинаем его шаблонизировать путем замены текста на переменные синтаксиса типа ${data}

У нас будут следующие переменные, которые мы будем подставлять в документ:

${num_dogovor} — номер догвоора
${city} — город
${date} — текущая дата
${name} — ФИО
${company} — Название Организации ООО
${summa} — Сумма
${summa_str} — Сумма, прописью
${summa_nalog} — Налог, 6% от суммы 
${summa_nalog_str} — Налог, 6% от суммы (прописью)
${ur_address} — Юр. адрес
${post_address} — Почтовый адрес
${company_ogrn} — ОГРН
${company_okpo​​​​​​​} — ОКПО
${company_kpp​​​​​​​} — КПП
${company_inn​​​​​​​} — ИНН организации
${company_bank​​​​​​​} — Название банка
${company_ks​​​​​​​} — кор. счет
${company_rs​​​​​​​} — р. счет
${direktor​​​​​​​} — ФИО директора

Далее скачиваем библиотеку PhpWord

//Подключаем библиотеку
require $_SERVER["DOCUMENT_ROOT"].'/lib/phpword/autoload.php';

//создаем класс
$phpWord = new  PhpOfficePhpWordPhpWord(); 
$_doc = new PhpOfficePhpWordTemplateProcessor('template.docx');

Синтаксис для замены переменных

$_doc->setValue('num_dogovor', $number_document); 

Подготовим пару переменных

//запихиваем сумму в переменную, что бы далее с ней поработать
$summa = 25550;

// делаем красивый формат
$summa_format = number_format($summa, 2, ',', ' ');

// вычислим налог от суммы (6%) и так же определим в отдельную переменную красивый формат суммы
$summa_nalog = $summa * 6 / 100; 
$summa_nalog_format = number_format($summa_nalog, 2, ',', ' ');

Подставляем, заменяем переменные в word документ

$_doc->setValue('num_dogovor', $number_document); 
$_doc->setValue('city', "г. Сочи"); 
$_doc->setValue('name', "Масков Илон Гениальнович"); 
$_doc->setValue('date', date("d.m.Y")); 
$_doc->setValue('company', "ООО НЕ ПРОХОДИТЕ МИМО"); 
$_doc->setValue('summa', $summa_format); 
$_doc->setValue('summa_str', num2str($summa));
$_doc->setValue('summa_nalog', $summa_nalog);
$_doc->setValue('summa_nalog_str', num2str($summa_nalog));
$_doc->setValue('company_ogrn', "ОГРН компании");
$_doc->setValue('company_inn', "ИНН компании");
$_doc->setValue('company_kpp', "КПП компании");
$_doc->setValue('company_bank', "Какое то название банка");
$_doc->setValue('company_bik', "бик банка");
$_doc->setValue('company_ks', "12342352456235");
$_doc->setValue('company_rs', "66666666666");
$_doc->setValue('ur_address', "Юридический адрес, какой-нибудь");
$_doc->setValue('post_address', "Фактический адрес");
$_doc->setValue('direktor', "Альберт Енштейн");
$_doc->setValue('company_okpo', "4444444");

Сохраняем сгенерированный word файл на сервер

$img_Dir_Str = "/files/";
$img_Dir = $_SERVER['DOCUMENT_ROOT']."/". $img_Dir_Str; 
@mkdir($img_Dir, 0777);
$file = str_replace("/","-", "Договор №".date("d-m-Y")).".docx";

$_doc->saveAs($img_Dir.$file);

Обратите внимание на строку: $_doc->setValue('summa_str', num2str($summa)); и   $_doc->setValue('summa_nalog_str', num2str($summa_nalog));

В ней мы используем функцию перевода числа в прописной вид

Функция перевода числа в прописной вид

function num2str($num) {
	$nul='ноль';
	$ten=array(
		array('','один','два','три','четыре','пять','шесть','семь', 'восемь','девять'),
		array('','одна','две','три','четыре','пять','шесть','семь', 'восемь','девять'),
	);
	$a20=array('десять','одиннадцать','двенадцать','тринадцать','четырнадцать' ,'пятнадцать','шестнадцать','семнадцать','восемнадцать','девятнадцать');
	$tens=array(2=>'двадцать','тридцать','сорок','пятьдесят','шестьдесят','семьдесят' ,'восемьдесят','девяносто');
	$hundred=array('','сто','двести','триста','четыреста','пятьсот','шестьсот', 'семьсот','восемьсот','девятьсот');
	$unit=array( // Units
		array('коп.' ,'коп.' ,'коп.',	 1),
		array('рубль'   ,'рубля'   ,'рублей'    ,0),
		array('тысяча'  ,'тысячи'  ,'тысяч'     ,1),
		array('миллион' ,'миллиона','миллионов' ,0),
		array('миллиард','милиарда','миллиардов',0),
	);
	//
	list($rub,$kop) = explode('.',sprintf("%015.2f", floatval($num)));
	$out = array();
	if (intval($rub)>0) {
		foreach(str_split($rub,3) as $uk=>$v) { // by 3 symbols
			if (!intval($v)) continue;
			$uk = sizeof($unit)-$uk-1; // unit key
			$gender = $unit[$uk][3];
			list($i1,$i2,$i3) = array_map('intval',str_split($v,1));
			// mega-logic
			$out[] = $hundred[$i1]; # 1xx-9xx
			if ($i2>1) $out[]= $tens[$i2].' '.$ten[$gender][$i3]; # 20-99
			else $out[]= $i2>0 ? $a20[$i3] : $ten[$gender][$i3]; # 10-19 | 1-9
			// units without rub & kop
			if ($uk>1) $out[]= morph($v,$unit[$uk][0],$unit[$uk][1],$unit[$uk][2]);
		} //foreach
	}
	else $out[] = $nul;
	$out[] = morph(intval($rub), $unit[1][0],$unit[1][1],$unit[1][2]); // rub
	$out[] = $kop.' '.morph($kop,$unit[0][0],$unit[0][1],$unit[0][2]); // kop
	return trim(preg_replace('/ {2,}/', ' ', join(' ',$out)));
}

/**
 * Склоняем словоформу
 * @ author runcore
 */
function morph($n, $f1, $f2, $f5) {
	$n = abs(intval($n)) % 100;
	if ($n>10 && $n<20) return $f5;
	$n = $n % 10;
	if ($n>1 && $n<5) return $f2;
	if ($n==1) return $f1;
	return $f5;
}

Статья подготовлена для Вас сайтом kisameev.ru

Перевел: Кисамеев Дмитрий

Урок создан: 3 октября 2021 г.

Статью просмотрели: 8649

Понравилось: 17

Welcome to a quick tutorial on how to convert HTML to DOCX using PHP. Need to generate formal Word reports? Capture a webpage into a document? Yes, that can actually be done pretty easily.

In order to convert HTML to DOCX in PHP, we have to download and use a third-party library. PHPWord is a good choice, and we can use Composer to get the latest version – composer require phpoffice/phpword. Thereafter, a short code snippet to generate DOCX from HTML:

  • require "vendor/autoload.php";
  • $pw = new PhpOfficePhpWordPhpWord();
  • $section = $pw->addSection();
  • PhpOfficePhpWordSharedHtml::addHtml($section, "<span>FOO</span>", false, false);
  • $pw->save("HTML.docx", "Word2007");

That’s the gist of it, but let us walk through more detailed examples in this guide – Read on!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

TLDR – QUICK SLIDES

Convert HTML To DOCX In PHP

Fullscreen Mode – Click Here

TABLE OF CONTENTS

DOWNLOAD & NOTES

First, here is the download link to the example source code as promised.

QUICK NOTES

  • A copy of PHPWord is not included in the zip file. Please download and get the latest version from their website.
  • Run 2-convert.php and 3-more.php for the conversion demo.

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

All right, let us now get into the example of how to convert HTML into a DOCX document in PHP.

STEP 1) DOWNLOAD PHPWORD

  • PHP is unable to generate DOCX documents natively. To do that, we are going to use an open-source library called PHPWord.
  • The easiest way to get it is to use a package manager called Composer. A small hassle, but Composer does offer quite a bit of convenience for a ton of libraries.
  • After you have installed Composer, navigate to your project folder in the command prompt (or terminal).
  • Run composer require phpoffice/phpword, and watch it will automatically get the latest version into the vendor/ folder.
  • Check out the official PHPWord documentation for more code examples and references.

STEP 2) PHP CONVERT HTML TO DOCX

2-convert.php

<?php
// (A) LOAD PHPWORD
require "vendor/autoload.php";
$pw = new PhpOfficePhpWordPhpWord();
 
// (B) ADD HTML CONTENT
$section = $pw->addSection();
$html = "<h1>HELLO WORLD!</h1>";
$html .= "<p>This is a paragraph of random text</p>";
$html .= "<table><tr><td>A table</td><td>Cell</td></tr></table>";
PhpOfficePhpWordSharedHtml::addHtml($section, $html, false, false);
 
// (C) SAVE TO DOCX ON SERVER
// $pw->save("convert.docx", "Word2007");
 
// (D) OR FORCE DOWNLOAD
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment;filename="convert.docx"");
$objWriter = PhpOfficePhpWordIOFactory::createWriter($pw, "Word2007");
$objWriter->save("php://output");

The script to generate the DOCX documents is ridiculously simple.

  • (A) Start by including the PHPWord library, and creating the object.
  • (B) Add a new section to the DOCX document, then simply insert your HTML code.
  • (C & D) Output the file, and that’s it!

EXTRA) PHPWORD SUPPORTS OTHER FILE FORMATS

3-more.php

<?php
// (A) LOAD PHPWORD
require "vendor/autoload.php";
$pw = new PhpOfficePhpWordPhpWord();

// (B) ADD HTML CONTENT
$section = $pw->addSection();
$html = "<h1>HELLO WORLD!</h1>";
$html .= "<p>This is a paragraph of random text</p>";
$html .= "<table><tr><td>A table</td><td>Cell</td></tr></table>";
PhpOfficePhpWordSharedHtml::addHtml($section, $html, false, false);

// (C) PHPWORD SUPPORTS MANY OTHER FORMATS!
$writers = [
  "Word2007" => "docx",
  "ODText" => "odt",
  "RTF" => "rtf",
  "HTML" => "html"
];
foreach ($writers as $format => $extension) {
  $target = "output.$extension";
  $pw->save($target, $format);
}

If you poke around the sample scripts that PHPWord provides in vendorphpofficephpwordsamples , you will notice that it is actually capable of more than just .DOCX – It can also create rich text files, open document text, and even PDFs. So be sure to make full use of it.

LINKS & REFERENCES

  • Need to convert HTML to PDF as well? Check out my other guide.
  • Need to output in Excel? Check out this guide.

TUTORIAL VIDEO

INFOGRAPHIC CHEAT SHEET

Convert HTML To DOCX in PHP (Click to enlarge)

THE END

Thank you for reading, and we have come to the end of this short guide. I hope that it has helped you with your project, and if there is stuff that you wish to add to this guide, please feel free to comment below. Good luck with your future projects and happy coding!

Выберите файл для преобразования

Перетащите файлы сюда. Максимальный размер файла 100 МБ или зарегистрируйтесь

Вы можете перевести html документ в doc и во множество других форматов с помощью бесплатного онлайн конвертера.

Как сконвертировать doc в html?

Icon of «Загрузите html-файл»

Шаг 1

Загрузите html-файл

Выберите файл, который вы хотите конвертировать с компьютера, Google Диска, Dropbox или перетащите его на страницу.

Icon of «Выберите «в doc»»

Шаг 2

Выберите «в doc»

Выберите doc или любой другой формат, в который вы хотите конвертировать файл (более 200 поддерживаемых форматов)

Icon of «Скачайте ваш doc файл»

Шаг 3

Скачайте ваш doc файл

Подождите пока ваш файл сконвертируется и нажмите скачать doc-файл

Бесплатное онлайн преобразование html в doc

Быстро и легко

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

Не беспокойтесь о безопасности

Мы удаляем загруженные файлы html мгновенно и преобразованные doc файлы через 24 часа. Все файлы передаются с использованием продвинутого шифрования SSL.

Все в облаке

Вам не нужно устанавливать какое-либо программное обеспечение. Все преобразования html в doc происходят в облаке и не используют какие-либо ресурсы вашего компьютера.

Hypertext Markup Language with a client-side image map

Расширение файла .html
Категория файла 🔵 documents
Программы

🔵 Internet Explorer

🔵 Mozilla Firefox

🔵 Google Chrome

🔵 Opera

🔵 Safari

🔵 Other internet browsers

Описание 🔵 HTML – специальный формат, связанный с веб-страницами, при разработке которых применялся соответствующий язык разметки. Множество станиц, соединенных ссылками, образуют веб-сайты. Файлы с подобным расширением изменяются текстовыми редакторами, так как представляют собой стандартный текстовый документ. Однако, чтобы избежать некорректного отображения рекомендуется использовать специализированное ПО, например, Adobe Dreamweaver. Открыть файлы HTML позволяют все современные браузеры, при этом по умолчанию исходный код не отображается. Его можно посмотреть в меню веб-браузера, выбрав категорию «Просмотр источника» либо с помощью текстового редактора.
Файлы с расширением HTML включают текстовое содержание и ссылки в виде текста на внешние объекты, например, картинку внутри статьи.
Технические детали 🔵 Язык HTML был создан Т. Бернерсом-Ли для обмена научно-технической информацией людьми, не имеющими глубоких знаний в области верстки. В его основе лежит использование множества тегов, обрамленных в угловые скобки. Современные браузеры без труда интерпретируют язык HTML4, предоставляя пользователю отформатированный текст. Сейчас появилась пятая версия со спецификацией DOM (ранее SGML).
Разработчик 🔵 World Wide Web Consortium & WHATWG
MIME type

🔵 text/html

Microsoft Word Document

Расширение файла .doc
Категория файла 🔵 documents
Программы

🔵 Microsoft Word

🔵 OpenOffice.org Writer

🔵 IBM Lotus Symphony

🔵 Apple Pages

🔵 AbiWord

Основная программа 🔵 Microsoft Word
Описание 🔵 DOC – специальное расширение, соответствующее документам, созданным в текстовом редакторе Microsoft World, до версии 2007 года. В этом формате хранятся сведения о форматировании текстового документа – абзацы, списки, отступы, выравнивания и многое другое. Файлы DOC могут включать в себя не только текстовую информацию, но и многочисленные изображения, графики, сценарии, диаграммы.
DOC представляет собой расширение в формате двоичного файла, который начинается с информационного блока, выступающего ключевым элементом всей совокупности файлов данных. Такие двоичные файлы включают в себя довольно большой объем информации о форматировании текстового документа.
Традиционно расширение получило широкое распространение для создания документов текстового формата в большом диапазоне ОС. Файлы в этом формате открываются любыми, в том числе современными версиями редактора Word или его аналогами из бесплатных пакетов вроде Open Office, Libre Office или утилитами наподобие Corel WordPerfect.
Технические детали 🔵 Первые версии файлового формата DOC приоритетно ориентировались на содержание форматированного текста, но со временем к нему добавилось большое количество встроенных объектов, среди которых встречаются как диаграммы и графики, так и различные медиа-файлы (звуки, видео). Файлы с расширением DOC способны содержать данные о слиянии, благодаря чему шаблон обработки слов может применяться вместе с таблицей либо базой данных.
Разработчик 🔵 Microsoft
MIME type

🔵 application/msword

🔵 application/kswps

FAQ

❓ Как я могу конвертировать html в doc?

Во-первых, выберите html файл, который вы хотите конвертировать или перетащить его. Во-вторых, выберите doc или любой другой формат, в который вы хотите преобразовать файл. Затем нажмите кнопку конвертировать и подождите, пока файл не преобразуется

⏳ Как долго я должен ждать, чтобы преобразовать html в doc?

Преобразование Изображение обычно занимает несколько секунд. Вы преобразовать html в doc очень быстро.

🛡️ Это безопасно конвертировать html в doc на OnlineConvertFree?

Конечно! Мы удалить загруженные и преобразованные файлы, так что никто не имеет доступ к вашей информации. Все типы преобразования на OnlineConvertFree (в том числе html в doc) 100% безопасны.

📱 Можно ли преобразовать html в doc без установки программного обеспечения?

Да! OnlineConvertFree не требует установки. Вы можете конвертировать любые файлы (в том числе html в doc) онлайн на вашем компьютере или мобильном телефоне.

Понравилась статья? Поделить с друзьями:
  • Перевод pdf файла в word документ
  • Перевод pdf в текст word онлайн бесплатно
  • Перевод pdf в word с формулами
  • Перевод pdf в word с редактированием текста бесплатно
  • Перевод pdf в word с распознаванием текста онлайн бесплатно