Как в php открыть word

PHPWord — чтение MSWord документов средствами PHP

От автора: не так давно на нашем сайте был опубликован урок по созданию документов MS Word средствами языка PHP, и с использованием специальной библиотеки PHPWord. Но в комментариях к данному видео – прозвучал вопрос, как при помощи данной библиотеки читать готовые документы, что собственно и подтолкнуло меня к записи данного урока, в котором мы с Вами научимся, используя выше указанную библиотеку, читать ранее созданные документы MSWord.

скачать исходникискачать урок

В данном уроке мы продолжаем изучать возможности PHPWord, а именно рассмотрим инструменты по чтению готовых документов MS Word. Хотел бы отметить, что сегодня мы будем работать с уже установленной библиотекой, потому как это уже второй урок по данной теме, а значит, на основах подробно останавливаться не будем. Поэтому рекомендую, перед просмотром данного видео ознакомиться с первой часть урока – PHPWord — создание MS Word документов средствами PHP.

Итак, заготовка, тестового скрипта состоит из одного единственного файла index.php, в коде которого выполнена установка библиотеки.

Итак, заготовка, тестового скрипта состоит из одного единственного файла index.php, в коде которого выполнена установка библиотеки.

require ‘vendor/autoload.php’;

Для начала создадим переменную, в которой будет храниться путь к документу MSWord, с которым мы будем работать.

$source = __DIR__.«/docs/text.docx»;

Далее, вспомним, что в начале работы с библиотекой необходимо создать объект главного класса PHPWord, но это в том случае если создается новый документ. Если же осуществляется чтение готового файла MS Word – объект указанного класса необходимо создать для интересующего документа, но перед этим его нужно прочитать.

Для чтения готовых документов в PHPWord предусмотрена группа классов, отвечающих за чтение документов различных форматов. А значит, первым делом создадим объект специального “класса-риддера“.

$objReader = PhpOfficePhpWordIOFactory::createReader(‘Word2007’);

Далее, используя данный объект – выполним чтение документа формата MS Word.

$phpWord = $objReader>load($source);

Таким образом, по сути, задача урока выполнена, так как документ прочитан и его данные располагаются в структуре только что созданного объекта $phpWord. Но давайте поговорим о том, как же получить данные хранящиеся в объекте.

По официальной документации любая информация документа MS Word, согласно библиотеке PHPWord, располагается в отдельных секциях. При этом каждая секция содержит определенный набор элементов – текст, таблица, изображение, ссылка и т.д. Элементы – же в свою очередь, так же могут быть сложными и включать в себя некий набор вложенных элементов, к примеру таблицы.

Поэтому, вызывая на исполнение метод getSections(), мы получаем доступ к секциям документа, при этом в качестве результата будет возвращен массив, а значит мы его можем обойти циклом foreach().

foreach($phpWord>getSections() as $section) {

$arrays = $section>getElements();

}

При этом в коде цикла, для каждой секции, получим массив входящих элементов, вызывая на исполнение метод getElements(). Так как возвращаемое значение – это массив, значит, используя выше указанный цикл, мы можем получить доступ к каждой его ячейке.

foreach($arrays as $e) {

}

При этом в переменной $e на каждой итерации цикла, содержится объект одного из элементов массива секций. Казалось бы, мы сразу можем получить текстовые данные MS Word, но для начала нужно проверить, что содержится в переменной $e.

if(get_class($e) === ‘PhpOfficePhpWordElementTextRun’) {

Если в данной переменной содержится объект класса ‘PhpOfficePhpWordElementTextRun’, значит мы работаем с сложной текстовой областью, в которой располагается несколько более простых элементов. Поэтому повторно вызываем метод getElements() и по результату проходимся в цикле foreach().

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

<?php

require ‘vendor/autoload.php’;

$source = __DIR__.«/docs/text.docx»;

$objReader = PhpOfficePhpWordIOFactory::createReader(‘Word2007’);

$phpWord = $objReader>load($source);

$body = »;

foreach($phpWord>getSections() as $section) {

$arrays = $section>getElements();

foreach($arrays as $e) {

if(get_class($e) === ‘PhpOfficePhpWordElementTextRun’) {

foreach($e>getElements() as $text) {

$font = $text>getFontStyle();

$size = $font>getSize()/10;

$bold = $font>isBold() ? ‘font-weight:700;’ :»;

$color = $font>getColor();

$fontFamily = $font>getName();

$body .= ‘<span style=»font-size:’ . $size . ’em;font-family:’ . $fontFamily . ‘; ‘.$bold.‘; color:#’.$color.‘»>’;

$body .= $text>getText().‘</span>’;

}

}

}

}

include ‘templ.php’;

Таким образом, для текущего документа, в переменную $text, попадает объект элемента Text, то есть элемент простейшего текст, для получения которого достаточно вызвать на исполнение метод getText(). Для получения информации о форматировании текущего элемента, необходимо обратиться к методу getFontStyle(), который вернет объект в закрытых свойствах которого содержится указанная информация. Соответственно для доступа к значениям этих свойств необходимо использовать специальные методы:

getSize() – размер шрифта;

isBold() — возвращает истину, если используется полужирный шрифт;

getColor() – цвет текста;

getName() – имя шрифта.

Все содержимое документа, записывается в переменную $body, значение которой будет отображено на экране, используя шаблон. Пустые строки документа представляют собой объект элемента TextBreak, который можно обработать следующим образом:

else if(get_class($e) === ‘PhpOfficePhpWordElementTextBreak’) {

$body .= ‘<br />’;

}

Для обработки таблиц, придется добавить достаточно много строк кода, потому как таблица – это сложный элемент Table, который состоит из отдельных строк, а те в свою очередь из отдельных ячеек. И более того, каждая ячейка, может содержать еще вложенные элементы, потому как, к примеру в одной ячейке так же можно сформировать таблицу. Ниже приведу весь код, вместе с кодом обработки таблиц.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

<?php

require ‘vendor/autoload.php’;

$source = __DIR__.«/docs/text.docx»;

$objReader = PhpOfficePhpWordIOFactory::createReader(‘Word2007’);

$phpWord = $objReader>load($source);

$body = »;

foreach($phpWord>getSections() as $section) {

$arrays = $section>getElements();

foreach($arrays as $e) {

if(get_class($e) === ‘PhpOfficePhpWordElementTextRun’) {

foreach($e>getElements() as $text) {

$font = $text>getFontStyle();

$size = $font>getSize()/10;

$bold = $font>isBold() ? ‘font-weight:700;’ :»;

$color = $font>getColor();

$fontFamily = $font>getName();

$body .= ‘<span style=»font-size:’ . $size . ’em;font-family:’ . $fontFamily . ‘; ‘.$bold.‘; color:#’.$color.‘»>’;

$body .= $text>getText().‘</span>’;

}

}

else if(get_class($e) === ‘PhpOfficePhpWordElementTextBreak’) {

$body .= ‘<br />’;

}

else if(get_class($e) === ‘PhpOfficePhpWordElementTable’) {

$body .= ‘<table border=»2px»>’;

$rows = $e>getRows();

foreach($rows as $row) {

$body .= ‘<tr>’;

$cells = $row>getCells();

foreach($cells as $cell) {

$body .= ‘<td style=»width:’.$cell>getWidth().‘»>’;

$celements = $cell>getElements();

foreach($celements as $celem) {

if(get_class($celem) === ‘PhpOfficePhpWordElementText’) {

$body .= $celem>getText();

}

else if(get_class($celem) === ‘PhpOfficePhpWordElementTextRun’) {

foreach($celem>getElements() as $text) {

$body .= $text>getText();

}

}

}

$body .= ‘</td>’;

}

$body .= ‘</tr>’;

}

$body .= ‘</table>’;

}

else {

$body .= $e>getText();

}

}

break;

}

include ‘templ.php’;

Для получения строк, необходимо вызвать метод getRows(), при этом в качестве результата будет возвращен массив объектов с информацией по каждой строке (элемент Row). Используя foreach(), обходим данный массив и для каждой строки получаем ячейки, при помощи метода getCells(). При этом опять же возвращается массив, который все так же мы обходим циклом. А далее для каждой ячейки вызываем на исполнение метод getElements(), для получения ее элементов. И так далее по принципу описанным выше.

Далее, осталось только отобразить значение переменной $body, любым удобным для Вас способом.

На этом данный урок я буду завершать. Как Вы видите, PHPWord предоставляет достаточно мощные инструменты по работе с документами MS Word, но и в тоже время сложные в плане получения данных из объектов.

Всего Вам доброго и удачного кодирования!!!

Is it possible to read and write Word (2003 and 2007) files in PHP without using a COM object?
I know that I can:

$file = fopen('c:file.doc', 'w+');
fwrite($file, $text);
fclose();

but Word will read it as an HTML file not a native .doc file.

asked Oct 9, 2008 at 18:09

UnkwnTech's user avatar

UnkwnTechUnkwnTech

87.1k65 gold badges183 silver badges229 bronze badges

1

Reading binary Word documents would involve creating a parser according to the published file format specifications for the DOC format. I think this is no real feasible solution.

You could use the Microsoft Office XML formats for reading and writing Word files — this is compatible with the 2003 and 2007 version of Word. For reading you have to ensure that the Word documents are saved in the correct format (it’s called Word 2003 XML-Document in Word 2007). For writing you just have to follow the openly available XML schema. I’ve never used this format for writing out Office documents from PHP, but I’m using it for reading in an Excel worksheet (naturally saved as XML-Spreadsheet 2003) and displaying its data on a web page. As the files are plainly XML data it’s no problem to navigate within and figure out how to extract the data you need.

The other option — a Word 2007 only option (if the OpenXML file formats are not installed in your Word 2003) — would be to ressort to OpenXML. As databyss pointed out here the DOCX file format is just a ZIP archive with XML files included. There are a lot of resources on MSDN regarding the OpenXML file format, so you should be able to figure out how to read the data you want. Writing will be much more complicated I think — it just depends on how much time you’ll invest.

Perhaps you can have a look at PHPExcel which is a library able to write to Excel 2007 files and read from Excel 2007 files using the OpenXML standard. You could get an idea of the work involved when trying to read and write OpenXML Word documents.

Community's user avatar

answered Nov 5, 2008 at 13:04

Stefan Gehrig's user avatar

Stefan GehrigStefan Gehrig

82.3k24 gold badges158 silver badges188 bronze badges

1

this works with vs < office 2007 and its pure PHP, no COM crap, still trying to figure 2007

<?php



/*****************************************************************
This approach uses detection of NUL (chr(00)) and end line (chr(13))
to decide where the text is:
- divide the file contents up by chr(13)
- reject any slices containing a NUL
- stitch the rest together again
- clean up with a regular expression
*****************************************************************/

function parseWord($userDoc) 
{
    $fileHandle = fopen($userDoc, "r");
    $line = @fread($fileHandle, filesize($userDoc));   
    $lines = explode(chr(0x0D),$line);
    $outtext = "";
    foreach($lines as $thisline)
      {
        $pos = strpos($thisline, chr(0x00));
        if (($pos !== FALSE)||(strlen($thisline)==0))
          {
          } else {
            $outtext .= $thisline." ";
          }
      }
     $outtext = preg_replace("/[^a-zA-Z0-9s,.-nrt@/_()]/","",$outtext);
    return $outtext;
} 

$userDoc = "cv.doc";

$text = parseWord($userDoc);
echo $text;


?>

UnkwnTech's user avatar

UnkwnTech

87.1k65 gold badges183 silver badges229 bronze badges

answered Nov 5, 2008 at 12:35

2

You can use Antiword, it is a free MS Word reader for Linux and most popular OS.

$document_file = 'c:file.doc';
$text_from_doc = shell_exec('/usr/local/bin/antiword '.$document_file);

answered May 23, 2009 at 0:57

Mantichora's user avatar

MantichoraMantichora

3854 silver badges8 bronze badges

5

I don’t know about reading native Word documents in PHP, but if you want to write a Word document in PHP, WordprocessingML (aka WordML) might be a good solution. All you have to do is create an XML document in the correct format. I believe Word 2003 and 2007 both support WordML.

answered Oct 10, 2008 at 0:23

Joe Lencioni's user avatar

Joe LencioniJoe Lencioni

10.2k17 gold badges54 silver badges66 bronze badges

Just updating the code

<?php

/*****************************************************************
This approach uses detection of NUL (chr(00)) and end line (chr(13))
to decide where the text is:
- divide the file contents up by chr(13)
- reject any slices containing a NUL
- stitch the rest together again
- clean up with a regular expression
*****************************************************************/

function parseWord($userDoc) 
{
    $fileHandle = fopen($userDoc, "r");
    $word_text = @fread($fileHandle, filesize($userDoc));
    $line = "";
    $tam = filesize($userDoc);
    $nulos = 0;
    $caracteres = 0;
    for($i=1536; $i<$tam; $i++)
    {
        $line .= $word_text[$i];

        if( $word_text[$i] == 0)
        {
            $nulos++;
        }
        else
        {
            $nulos=0;
            $caracteres++;
        }

        if( $nulos>1996)
        {   
            break;  
        }
    }

    //echo $caracteres;

    $lines = explode(chr(0x0D),$line);
    //$outtext = "<pre>";

    $outtext = "";
    foreach($lines as $thisline)
    {
        $tam = strlen($thisline);
        if( !$tam )
        {
            continue;
        }

        $new_line = ""; 
        for($i=0; $i<$tam; $i++)
        {
            $onechar = $thisline[$i];
            if( $onechar > chr(240) )
            {
                continue;
            }

            if( $onechar >= chr(0x20) )
            {
                $caracteres++;
                $new_line .= $onechar;
            }

            if( $onechar == chr(0x14) )
            {
                $new_line .= "</a>";
            }

            if( $onechar == chr(0x07) )
            {
                $new_line .= "t";
                if( isset($thisline[$i+1]) )
                {
                    if( $thisline[$i+1] == chr(0x07) )
                    {
                        $new_line .= "n";
                    }
                }
            }
        }
        //troca por hiperlink
        $new_line = str_replace("HYPERLINK" ,"<a href=",$new_line); 
        $new_line = str_replace("o" ,">",$new_line); 
        $new_line .= "n";

        //link de imagens
        $new_line = str_replace("INCLUDEPICTURE" ,"<br><img src=",$new_line); 
        $new_line = str_replace("*" ,"><br>",$new_line); 
        $new_line = str_replace("MERGEFORMATINET" ,"",$new_line); 


        $outtext .= nl2br($new_line);
    }

 return $outtext;
} 

$userDoc = "custo.doc";
$userDoc = "Cultura.doc";
$text = parseWord($userDoc);

echo $text;


?>

Bill the Lizard's user avatar

answered Apr 4, 2011 at 2:43

WIlson's user avatar

WIlsonWIlson

611 silver badge1 bronze badge

4

Most probably you won’t be able to read Word documents without COM.

Writing was covered in this topic

Community's user avatar

answered Oct 10, 2008 at 2:17

Sergey Kornilov's user avatar

Sergey KornilovSergey Kornilov

1,7722 gold badges13 silver badges22 bronze badges

2007 might be a bit complicated as well.

The .docx format is a zip file that contains a few folders with other files in them for formatting and other stuff.

Rename a .docx file to .zip and you’ll see what I mean.

So if you can work within zip files in PHP, you should be on the right path.

0

www.phplivedocx.org is a SOAP based service that means that you always need to be online for testing the Files also does not have enough examples for its use . Strangely I found only after 2 days of downloading (requires additionaly zend framework too) that its a SOAP based program(cursed me !!!)…I think without COM its just not possible on a Linux server and the only idea is to change the doc file in another usable file which PHP can parse…

answered Sep 13, 2009 at 17:45

Source gotten from

Use following class directly to read word document

class DocxConversion{
    private $filename;

    public function __construct($filePath) {
        $this->filename = $filePath;
    }

    private function read_doc() {
        $fileHandle = fopen($this->filename, "r");
        $line = @fread($fileHandle, filesize($this->filename));   
        $lines = explode(chr(0x0D),$line);
        $outtext = "";
        foreach($lines as $thisline)
          {
            $pos = strpos($thisline, chr(0x00));
            if (($pos !== FALSE)||(strlen($thisline)==0))
              {
              } else {
                $outtext .= $thisline." ";
              }
          }
         $outtext = preg_replace("/[^a-zA-Z0-9s,.-nrt@/_()]/","",$outtext);
        return $outtext;
    }

    private function read_docx(){

        $striped_content = '';
        $content = '';

        $zip = zip_open($this->filename);

        if (!$zip || is_numeric($zip)) return false;

        while ($zip_entry = zip_read($zip)) {

            if (zip_entry_open($zip, $zip_entry) == FALSE) continue;

            if (zip_entry_name($zip_entry) != "word/document.xml") continue;

            $content .= zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));

            zip_entry_close($zip_entry);
        }// end while

        zip_close($zip);

        $content = str_replace('</w:r></w:p></w:tc><w:tc>', " ", $content);
        $content = str_replace('</w:r></w:p>', "rn", $content);
        $striped_content = strip_tags($content);

        return $striped_content;
    }

 /************************excel sheet************************************/

function xlsx_to_text($input_file){
    $xml_filename = "xl/sharedStrings.xml"; //content file name
    $zip_handle = new ZipArchive;
    $output_text = "";
    if(true === $zip_handle->open($input_file)){
        if(($xml_index = $zip_handle->locateName($xml_filename)) !== false){
            $xml_datas = $zip_handle->getFromIndex($xml_index);
            $xml_handle = DOMDocument::loadXML($xml_datas, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
            $output_text = strip_tags($xml_handle->saveXML());
        }else{
            $output_text .="";
        }
        $zip_handle->close();
    }else{
    $output_text .="";
    }
    return $output_text;
}

/*************************power point files*****************************/
function pptx_to_text($input_file){
    $zip_handle = new ZipArchive;
    $output_text = "";
    if(true === $zip_handle->open($input_file)){
        $slide_number = 1; //loop through slide files
        while(($xml_index = $zip_handle->locateName("ppt/slides/slide".$slide_number.".xml")) !== false){
            $xml_datas = $zip_handle->getFromIndex($xml_index);
            $xml_handle = DOMDocument::loadXML($xml_datas, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
            $output_text .= strip_tags($xml_handle->saveXML());
            $slide_number++;
        }
        if($slide_number == 1){
            $output_text .="";
        }
        $zip_handle->close();
    }else{
    $output_text .="";
    }
    return $output_text;
}


    public function convertToText() {

        if(isset($this->filename) && !file_exists($this->filename)) {
            return "File Not exists";
        }

        $fileArray = pathinfo($this->filename);
        $file_ext  = $fileArray['extension'];
        if($file_ext == "doc" || $file_ext == "docx" || $file_ext == "xlsx" || $file_ext == "pptx")
        {
            if($file_ext == "doc") {
                return $this->read_doc();
            } elseif($file_ext == "docx") {
                return $this->read_docx();
            } elseif($file_ext == "xlsx") {
                return $this->xlsx_to_text();
            }elseif($file_ext == "pptx") {
                return $this->pptx_to_text();
            }
        } else {
            return "Invalid File Type";
        }
    }

}

$docObj = new DocxConversion("test.docx"); //replace your document name with correct extension doc or docx 
echo $docText= $docObj->convertToText();

answered Jul 3, 2019 at 10:25

Mohamed Faalil's user avatar

Office 2007 .docx should be possible since it’s an XML standard. Word 2003 most likely requires COM to read, even with the standards now published by MS, since those standards are huge. I haven’t seen many libraries written to match them yet.

answered Oct 10, 2008 at 2:45

acrosman's user avatar

acrosmanacrosman

12.8k10 gold badges40 silver badges55 bronze badges

I don’t know what you are going to use it for, but I needed .doc support for search indexing; What I did was use a little commandline tool called «catdoc»; This transfers the contents of the Word document to plain text so it can be indexed. If you need to keep formatting and stuff this is not your tool.

answered Oct 10, 2008 at 15:25

fijter's user avatar

fijterfijter

17.5k2 gold badges24 silver badges28 bronze badges

phpLiveDocx is a Zend Framework component and can read and write DOC and DOCX files in PHP on Linux, Windows and Mac.

See the project web site at:

Contact lenses Guide

answered May 14, 2009 at 7:03

1

One way to manipulate Word files with PHP that you may find interesting is with the help of PHPDocX.
You may see how it works having a look at its online tutorial.
You can insert or extract contents or even merge multiple Word files into a asingle one.

answered Sep 28, 2012 at 16:44

Eduardo's user avatar

Would the .rtf format work for your purposes? .rtf can easily be converted to and from .doc format, but it is written in plaintext (with control commands embedded). This is how I plan to integrate my application with Word documents.

answered Jan 24, 2009 at 5:09

Josh Smeaton's user avatar

Josh SmeatonJosh Smeaton

47.6k24 gold badges129 silver badges164 bronze badges

1

even i’m working on same kind of project [An Onlinw Word Processor]!
But i’ve choosen c#.net and ASP.net. But through the survey i did; i got to know that

By Using Open XML SDK and VSTO [Visual Studio Tools For Office]

we may easily work with a word file manipulate them and even convert internally to different into several formats such as .odt,.pdf,.docx etc..

So, goto msdn.microsoft.com and be thorough about the office development tab. Its the easiest way to do this as all functions we need to implement are already available in .net!!

But as u want to do ur project in PHP, u can do it in Visual Studio and .net as PHP is also one of the .net Compliant Language!!

answered Sep 5, 2010 at 14:17

Noddy Cha's user avatar

Noddy ChaNoddy Cha

8511 gold badge12 silver badges19 bronze badges

I have the same case
I guess I am going to use a cheap 50 mega windows based hosting with free domain to use it to convert my files on, for PHP server. And linking them is easy.
All you need is make an ASP.NET page that recieves the doc file via post and replies it via HTTP
so simple CURL would do it.

answered Oct 11, 2010 at 19:12

Omer's user avatar

1

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.

10.07.18 ИТ / PHP 13413

Сайт сегодня – это непросто странички, а в большинстве случаев целая система по обработке и генерации различных данных. Часто бывает необходимо вывести данные с сайта в какой-либо распространенный формат, например, в PDF, DOCX, CSV и т.д. Рассмотрим, как можно вывести данные в файл DOCX на PHP.

Немного о формате DOCX. Это расширение файлов для программы Microsoft Office, продукт Word. Microsoft Word представляет собой текстовый процессор, который предназначен для создания, просмотра и редактирования текстовых документов. Раньше Word в основном использовался двоичный формат сохранения файлов, расширение DOC. Но, на смену ему пришел более совершенный формат – DOCX. Как устроен DOCX?

DOCX – это просто архив, в котором содержатся все необходимые файлы для документа, сам документ хранится в формате XML. Это делает возможным легко открыть архив на PHP и вывести нужные данные в файл XML внутри контейнера DOCX. Чтобы лучше понять, что содержится в таком файле, можно взять любой архиватор и открыть с его помощью файл DOCX. Внутри Вы увидите определенную структуру из папок и файлов.

docx-structure

Основной интерес представляет собой папка word, в ней то и содержится основное содержимое файла DOCX. Как видно, все файлы и настройки в этом формате стремились сделать с расширением XML, это неспроста, ведь X на конце означает отношение к XML. На рисунке ниже можно увидеть содержимое папки word, главный файл здесь document.xml.

docx-structure-word

Именно файл document.xml и содержит весь основной контент документа DOCX. Работать с форматом XML достаточно просто при помощи любых средств, ведь этот формат напоминает обычный текст, только он четко структурирован, что позволяет легко обратиться в любую точку файла и изменить любые данные.

Чтобы открыть DOCX на PHP и записать туда нужные данные, можно использовать довольно простой код:

$docx = new ZipArchive();

if ($docx->open('path_to_file/file.docx') === true) {	
	$xml = $docx->getFromName('word/document.xml');
	
	$xml = str_replace('[ИСКОМЫЙ ТЕКСТ]', 'ЗАМЕЩАЮЩИЙ ТЕКСТ', $xml);
	
	$docx->addFromString('word/document.xml', $xml);	
	
	$docx->close();
}

Сначала создается объект ZIP архива, в который затем считывается содержимое DOCX, из DOCX извлекается контент document.xml. Затем происходит непосредственная запись данных в файл, просто ищется заранее подготовленное место в файле DOCX в виде токена [ИСКОМЫЙ ТЕКСТ] и на его место записываются любые данные. После выполнения этой операции, происходит запись обновленного document.xml в DOCX и архив закрывается.

Важно проследить за целостностью токенов, если текст заменятся таким способом. Сделать это можно достаточно просто. Сначала откройте нужный файл в Word и расставьте токены, желательно написать их в простом блокноте и затем вставлять на нужные позиции. После чего, сохраните файл DOCX и откройте его архиватором, найдите и откройте в нем document.xml – проверьте целостность токенов, они должны быть написаны слитно, без разрывов. Только в таком случае, возможна корректная замена токенов на нужный текст.

Таким образом, было рассмотрено устройство формата DOCX, а также показано, как можно легко записать данные в DOCX на 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 объекта

How to read and view docx Files using PHP. Now days processing Word Document is becoming more popular. Even you can create a new Word Document and process with it. My previous article describes you to create Word Document by using PHP.

Today we are going to discuss about reading the Docx files and convert it into text and view it online. Let’s begin with steps and codes,

<?php
function kv_read_word($input_file){	
	 $kv_strip_texts = ''; 
         $kv_texts = ''; 	
	if(!$input_file || !file_exists($input_file)) return false;
		
	$zip = zip_open($input_file);
		
	if (!$zip || is_numeric($zip)) return false;
	
	
	while ($zip_entry = zip_read($zip)) {
			
		if (zip_entry_open($zip, $zip_entry) == FALSE) continue;
			
		if (zip_entry_name($zip_entry) != "word/document.xml") continue;

		$kv_texts .= zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
			
		zip_entry_close($zip_entry);
	}
	
	zip_close($zip);
		

	$kv_texts = str_replace('</w:r></w:p></w:tc><w:tc>', " ", $kv_texts);
	$kv_texts = str_replace('</w:r></w:p>', "rn", $kv_texts);
	$kv_strip_texts = nl2br(strip_tags($kv_texts,’‘));

	return $kv_strip_texts;
}
?>

The above function will helps you to get parse the text’s in a Word Document and  return it.

Now, we need to give the input file and its path as input to the function and print it for results.

<?php
$kv_texts = kv_read_word('path/to/the/file/kvcodes.docx');
if($kv_texts !== false) {		
	echo nl2br($kv_texts);	
}
else {
	echo 'Can't Read that file.';
}
?>

That’s it to read a docx file  and print it as text.

I have another article for WordPress user, who can try this to process Docx files using php and WordPress

How to Read and get Texts from Docx Files in WordPress

Время от времени многим программистам приходится сталкиваться с такими задачами, как создание word или pdf файлов средствами PHP. Если со вторым ощутимых проблем нет, так как есть хорошая библиотека, то с Word-ом дела обстоят сложнее.

Чтобы создать word файл можно использовать специальную библиотеку или пойти более хитрым путем. О нем и пойдет речь.

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

Для этого нужно подготовить word шаблон и сохранить как xml файл. Затем средствами php мы будем открывать xml файл и делать замену нужных строк на необходимые и сохранять файл в виде .doc расширения. Таким образом, любой пользователь сможет без ошибок открыть сгенерированный word и работать с ним.

Единственной сложностью такого подхода остается разобраться с кодом самого word-а в xml виде, так как в нем будет много мусора. Для этого вам нужно будет постоянно создавать word файлы и прописывать слова, теги, свойства, таблицы. А в xml версии смотреть, как выглядит тот или иной код, чтобы затем его использовать для генерации шаблонов. Советую прописывать в ворде слова очень аккуратно, например, если нажмете backspace на букве или enter, то слово может разбиться на несколько групп в разных тегах. Поэтому для xml версии — чем проще пишите в word, тем лучше его xml версия.

По моим наблюдениям тело word-а всегда в тегах <w:body></w:body>. Поэтому внутри них и находится содержимое.

Пара примеров:

Текст: <w:p w:rsidR=»00822E93″ w:rsidRDefault=»003428FA»><w:r><w:t>Первый текст</w:t></w:r></w:p>

Перевод строк: <w:p w:rsidR=»00655BB2″ w:rsidRDefault=»00655BB2″><w:pPr><w:rPr><w:lang w:val=»en-US»/></w:rPr></w:pPr></w:p>

Таблица похожа на обычный table в html:

<w:tbl> = <table>
<w:tr> = <tr>
<w:tc> = <td>

Напоследок оставлю бонус собственного производства.

Разместите папку word, например, в корень вашего сайта и запустите index.php. Скрипт не только создаст на основе word.xml файл zakaz.doc, но и автоматически скачает его. Вам останется только открыть через word сгенерированный документ. Сама генерация идет в index.php. Для примера добавил помимо обычных строк таблицу, в которой вы сможете добавлять свои значения. Табличка динамическая. Это означает, что вы сможете добавлять в нее бесконечное количество товаров. Кстати, никто не мешает вам использовать генерацию прямо из БД вашего сайта. Это может быть очень удобным.

Можно ли читать и записывать файлы Word (2003 и 2007) на PHP без использования COM-объекта? Я знаю, что можно сделать так:

$file = fopen(‘c:file.doc’, ‘w+’);

fwrite($file, $text);

fclose();

но Word будет читать его как HTML-файл, а не как собственный файл .doc.

Ответ 1

Чтение двоичных документов Word потребовало бы создания анализатора в соответствии с опубликованными спецификациями формата файлов DOC. Я думаю, что это не является реально выполнимым решением. Вы можете использовать форматы Microsoft Office XML для чтения и записи файлов Word они совместимы с версиями Word 2003 и 2007. Для чтения необходимо убедиться, что документы Word сохранены в правильном формате (он называется Word 2003 XML-Document в Word 2007). Для записи достаточно следовать общедоступной XML-схеме. Я никогда не использовал этот формат для записи документов Office из PHP, но я использую его для чтения рабочего листа Excel (естественно, сохраненного как XML-Spreadsheet 2003) и отображения его данных на веб-странице. Поскольку файлы представляют собой обычные XML-данные, не составляет труда сориентироваться в них и понять, как извлечь нужные данные. Другой вариант вариант только для Word 2007 (если форматы файлов OpenXML не установлены в вашем Word 2003) это пересортировка в OpenXML. Формат файла DOCX это просто ZIP-архив с включенными XML-файлами. На MSDN есть много ресурсов по формату файлов OpenXML, так что вы должны быть в состоянии понять, как читать нужные вам данные. Запись будет намного сложнее, я думаю, все зависит от того, сколько времени вы потратите на это. Возможно, вы можете взглянуть на PHPExcel библиотеку, способную писать в файлы Excel 2007 и читать из файлов Excel 2007, используя стандарт OpenXML. Вы можете получить представление о работе, связанной с чтением и записью документов OpenXML Word.

Ответ 2

Данное решение работает с vs < office 2007, и это чистый PHP без всякого COM:

<?php

 /*****************************************************************

Этот подход использует обнаружение NUL (chr(00)) и конца строки (chr(13))

чтобы определить, где находится текст:

— разделяем содержимое файла на фрагменты по chr(13)

— отбрасываем все фрагменты, содержащие NUL

— сшиваем оставшиеся вместе

— очищаем с помощью регулярного выражения

*****************************************************************/

function parseWord($userDoc)  {

    $fileHandle = fopen($userDoc, «r»);

    $line = @fread($fileHandle, filesize($userDoc));   

    $lines = explode(chr(0x0D),$line);

    $outtext = «»;

    foreach($lines as $thisline) {

        $pos = strpos($thisline, chr(0x00));

        if (($pos !== FALSE)||(strlen($thisline)==0)) {

          } else {

            $outtext .= $thisline.» «;

          }

      }

     $outtext = preg_replace(«/[^a-zA-Z0-9s,.-nrt@/_()]/»,»»,$outtext);

    return $outtext;

$userDoc = «cv.doc»;

$text = parseWord($userDoc);

echo $text;

?>

Ответ 3

Просто обновляем код из предыдущего ответа:

<?php

 /*****************************************************************

Этот подход использует обнаружение NUL (chr(00)) и конца строки (chr(13))

чтобы определить, где находится текст:

— разделяем содержимое файла на фрагменты по chr(13)

— отбрасываем все фрагменты, содержащие NUL

— сшиваем оставшиеся вместе

— очищаем с помощью регулярного выражения

*****************************************************************/

function parseWord($userDoc)  {

    $fileHandle = fopen($userDoc, «r»);

    $word_text = @fread($fileHandle, filesize($userDoc));

    $line = «»;

    $tam = filesize($userDoc);

    $nulos = 0;

    $caracteres = 0;

    for($i=1536; $i<$tam; $i++) {

        $line .= $word_text[$i];

        if( $word_text[$i] == 0) {

            $nulos++;

        } else {

            $nulos=0;

            $caracteres++;

        }

        if( $nulos>1996)

        {   

            break;  

        }

    }

    //echo $caracteres;

    $lines = explode(chr(0x0D),$line);

    //$outtext = «<pre>»;

    $outtext = «»;

    foreach($lines as $thisline) {

        $tam = strlen($thisline);

        if( !$tam ) {

            continue;

        }

        $new_line = «»; 

        for($i=0; $i<$tam; $i++) {

            $onechar = $thisline[$i];

            if( $onechar > chr(240) ) {

                continue;

            }

            if( $onechar >= chr(0x20) ) {

                $caracteres++;

                $new_line .= $onechar;

            }

            if( $onechar == chr(0x14) ) {

                $new_line .= «</a>»;

            }

            if( $onechar == chr(0x07) ) {

                $new_line .= «t»;

                if( isset($thisline[$i+1]) ) {

                    if( $thisline[$i+1] == chr(0x07) ) {

                        $new_line .= «n»;

                    }

                }

            }

        }

        //troca por hiperlink

        $new_line = str_replace(«HYPERLINK» ,»<a href=»,$new_line); 

        $new_line = str_replace(«o» ,»>»,$new_line); 

        $new_line .= «n»;

        //link de imagens

        $new_line = str_replace(«INCLUDEPICTURE» ,»<br><img src=»,$new_line); 

        $new_line = str_replace(«*» ,»><br>»,$new_line); 

        $new_line = str_replace(«MERGEFORMATINET» ,»»,$new_line); 

        $outtext .= nl2br($new_line);

    }

    return $outtext;

$userDoc = «custo.doc»;

$userDoc = «Cultura.doc»;

$text = parseWord($userDoc);

echo $text;

?>

Ответ 4

www.phplivedocx.org это сервис на основе SOAP, который выполняет онлайнтестирование файлов. Файлы также имеют достаточно примеров для его использования. Я думаю, что без COM это просто невозможно на Linuxсервере, и единственная идея изменить doc файл в другой файл, который PHP может разобрать…

Ответ 5

Используя Open XML SDK и VSTO [Visual Studio Tools For Office], мы можем легко работать с файлами Word, манипулировать ими и даже конвертировать внутри в различные форматы, такие как .odt,.pdf,.docx и т. д. Итак, зайдите на сайт msdn.microsoft.com и внимательно изучите вкладку office development. Это самый простой способ сделать это, так как все функции, которые нам нужно реализовать, уже доступны в .net!!! Но так как вы хотите сделать свой проект на PHP, вы можете сделать это в Visual Studio и .net, потому как PHP также является одним из .net Compliant Language!!!

Ответ 6

Используйте следующий класс непосредственно для чтения документа Word:

class DocxConversion{

    private $filename;

    public function __construct($filePath) {

        $this->filename = $filePath;

    }

    private function read_doc() {

        $fileHandle = fopen($this->filename, «r»);

        $line = @fread($fileHandle, filesize($this->filename));   

        $lines = explode(chr(0x0D),$line);

        $outtext = «»;

        foreach($lines as $thisline) {

            $pos = strpos($thisline, chr(0x00));

            if (($pos !== FALSE)||(strlen($thisline)==0)) {

              } else {

                $outtext .= $thisline.» «;

              }

          }

         $outtext = preg_replace(«/[^a-zA-Z0-9s,.-nrt@/_()]/»,»»,$outtext);

        return $outtext;

    }

    private function read_docx(){

        $striped_content = »;

        $content = »;

        $zip = zip_open($this->filename);

        if (!$zip || is_numeric($zip)) return false;

        while ($zip_entry = zip_read($zip)) {

            if (zip_entry_open($zip, $zip_entry) == FALSE) continue;

            if (zip_entry_name($zip_entry) != «word/document.xml») continue;

            $content .= zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));

            zip_entry_close($zip_entry);

        }// end while

        zip_close($zip);

        $content = str_replace(‘</w:r></w:p></w:tc><w:tc>’, » «, $content);

        $content = str_replace(‘</w:r></w:p>’, «rn», $content);

        $striped_content = strip_tags($content);

        return $striped_content;

    }

 /************************excel sheet************************************/

function xlsx_to_text($input_file){

    $xml_filename = «xl/sharedStrings.xml»; //content file name

    $zip_handle = new ZipArchive;

    $output_text = «»;

    if(true === $zip_handle->open($input_file)){

        if(($xml_index = $zip_handle->locateName($xml_filename)) !== false){

            $xml_datas = $zip_handle->getFromIndex($xml_index);

            $xml_handle = DOMDocument::loadXML($xml_datas, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);

            $output_text = strip_tags($xml_handle->saveXML());

        }else{

            $output_text .=»»;

        }

        $zip_handle->close();

    }else{

    $output_text .=»»;

    }

    return $output_text;

}

/*************************power point files*****************************/

function pptx_to_text($input_file){

    $zip_handle = new ZipArchive;

    $output_text = «»;

    if(true === $zip_handle->open($input_file)){

        $slide_number = 1; //loop through slide files

        while(($xml_index = $zip_handle->locateName(«ppt/slides/slide».$slide_number.».xml»)) !== false){

            $xml_datas = $zip_handle->getFromIndex($xml_index);

            $xml_handle = DOMDocument::loadXML($xml_datas, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);

            $output_text .= strip_tags($xml_handle->saveXML());

            $slide_number++;

        }

        if($slide_number == 1){

            $output_text .=»»;

        }

        $zip_handle->close();

    }else{

    $output_text .=»»;

    }

    return $output_text;

}

    public function convertToText() {

       if(isset($this->filename) && !file_exists($this->filename)) {

            return «File Not exists»;

        }

        $fileArray = pathinfo($this->filename);

        $file_ext  = $fileArray[‘extension’];

        if($file_ext == «doc» || $file_ext == «docx» || $file_ext == «xlsx» || $file_ext == «pptx») {

            if($file_ext == «doc») {

                return $this->read_doc();

            } elseif($file_ext == «docx») {

                return $this->read_docx();

            } elseif($file_ext == «xlsx») {

                return $this->xlsx_to_text();

            }elseif($file_ext == «pptx») {

                return $this->pptx_to_text();

            }

        } else {

            return «Invalid File Type»;

        }

    }

}

$docObj = new DocxConversion(«test.docx»); //замените имя документа правильным расширением doc или docx

echo $docText= $docObj->convertToText();

Понравилась статья? Поделить с друзьями:
  • Как в php открыть excel файл
  • Как в outlook открыть файл excel
  • Как в openoffice writer сохранить openoffice word
  • Как в ole открыть excel
  • Как в mysql загрузить таблицы excel