Прочитать содержимое файла phpword
When I read docx and then save it, it doesn't look like original document. It has no equal styles for text block and tables and there are new line breaks.
Example with simple tables:
Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.
The text was updated successfully, but these errors were encountered:
3 Answers 3
Try to create your reader before
Answer is based on this example and API documentation
I have tried saving this same file as a .docx file and opening it with a Word2007 reader, and this works perfectly. Its only if I save the document as a .doc file and open it with the MsDoc reader that it reads half the content.
@Bohr this sounds as an internal reader issue of MsDoc . Trying to open your initial file .doc with Word2007 as your default reader might solve your problem for now. I don't know if you have tried this already though.
Rather than check each class for text, you can use
Small addition to above: there can also be TextRun elements with Text elements inside; so you would have to do this recursively to get all texts.
It can be installed on Ubuntu using
Once you have catdoc working on your system you can call it from php using shell_exec()
Be sure to substitute (fullpath) with the actual path to catdoc and your word doc.
EDIT ---- Addition
If you can save your files as .docx rather than .doc it is a little bit easier. You can use unzip rather than catdoc.
You could use this same technique with most other command line document to text converters. Just replace the command in the shell_exec() with the command that works on your system. You can check How to extract just plain text from .doc & .docx files? (unix) for other unix/linux alternatives
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:
With PHPWord, you can create OOXML, ODF, or RTF documents dynamically using your PHP 5.3.3+ 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
PHPWord requires the following:
- PHP 5.3.3+ (optional, used to write OOXML and ODF) (optional, used to add images) (optional, used to write OOXML and ODF) (optional, used to apply XSL style sheet to template ) (optional, used to write PDF)
PHPWord is installed via Composer. To add a dependency to PHPWord in your project, either
Run the following to use the latest stable version
or if you want the latest master version
You can of course also manually edit your composer.json file
The following is a basic usage example of the PHPWord library.
We welcome everyone to contribute to PHPWord. Below are some of the things that you can do to contribute.
Установка PHPWord
Установка PHPWord, может быть выполнена двумя способами. Первый способ – ручной, при котором Вы скачиваете архив с последней актуальной версией PHPWord, далее, выполняете распаковку, копируете файлы в собственный проект и подключаете на соответствующих страницах. То есть достаточно стандартный способ. И второй – так сказать, автоматический способ установки, используя инструмент Composer, который мы будем использовать в данном уроке.
Кстати, Вы, наверное, заметили, что в своих уроках, для установки различных библиотек, я призываю Вас использовать Composer. Так как для простых проектов, в ручную, вполне можно скачивать необходимые элементы, но если мы работаем над более сложным скриптом, то порой затруднительно скачать все необходимые элементы и правильно их установить.
Итак, открываем командную строку и переходим в каталог нашего проекта, используя команду “CD имя папки”.
Далее, используя конструкцию “composer require”, указываем от какой библиотеки “зависит” наш проект и выполняем инструкцию.
I want to extract the text content from the word document with PHP.
I have created a new word document in Microsoft Word for Mac 2011. Edit: have also tested by creating the same document in Microsoft Word under Windows 7.
The contents of the document is
I have saved it to disk as a Word 97-2004 Document (.doc).
I'm using phpoffice/phpword and this code to extract the text:
The output of this code is only parts of the text:
Is there a problem with the code, or is it some kind of compatibility issue?
If I add a var_dump($els); before foreach ($els as $e) < the output is this:
It looks like Unicode/ASCII incompatibility because the output has half length comparing to the original.
From the PHPWord GitHub page: "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." Your .doc type does not fall into any of these, I don't think.
Piuliss commented Dec 19, 2017 •
I have the same problem
this is changing completly the file, and all the style are missed. The footer is added
cubicleWar commented Jan 3, 2018
@troosan I am using dev-develop and still experiencing this bug. The template processor can open and save the file without issues but using IOFactory causes the loss of all images, styles and header/footer formatting.
tonybao121 commented May 20, 2020
I also have this problem. Using IOFactory to load a .docx file and wanted to save it into pdf but lose all my style and formatting :(
От автора: не так давно на нашем сайте был опубликован урок по созданию документов MS Word средствами языка PHP, и с использованием специальной библиотеки PHPWord. Но в комментариях к данному видео – прозвучал вопрос, как при помощи данной библиотеки читать готовые документы, что собственно и подтолкнуло меня к записи данного урока, в котором мы с Вами научимся, используя выше указанную библиотеку, читать ранее созданные документы MSWord.
В данном уроке мы продолжаем изучать возможности PHPWord, а именно рассмотрим инструменты по чтению готовых документов MS Word. Хотел бы отметить, что сегодня мы будем работать с уже установленной библиотекой, потому как это уже второй урок по данной теме, а значит, на основах подробно останавливаться не будем. Поэтому рекомендую, перед просмотром данного видео ознакомиться с первой часть урока – PHPWord — создание MS Word документов средствами PHP.
Итак, заготовка, тестового скрипта состоит из одного единственного файла index.php, в коде которого выполнена установка библиотеки.
Бесплатный курс по PHP программированию
Освойте курс и узнайте, как создать веб-приложение на PHP с полного нуля
Итак, заготовка, тестового скрипта состоит из одного единственного файла index.php, в коде которого выполнена установка библиотеки.
Для начала создадим переменную, в которой будет храниться путь к документу MSWord, с которым мы будем работать.
Далее, вспомним, что в начале работы с библиотекой необходимо создать объект главного класса PHPWord, но это в том случае если создается новый документ. Если же осуществляется чтение готового файла MS Word – объект указанного класса необходимо создать для интересующего документа, но перед этим его нужно прочитать.
Для чтения готовых документов в PHPWord предусмотрена группа классов, отвечающих за чтение документов различных форматов. А значит, первым делом создадим объект специального “класса-риддера“.
Далее, используя данный объект – выполним чтение документа формата MS Word.
Таким образом, по сути, задача урока выполнена, так как документ прочитан и его данные располагаются в структуре только что созданного объекта $phpWord. Но давайте поговорим о том, как же получить данные хранящиеся в объекте.
По официальной документации любая информация документа MS Word, согласно библиотеке PHPWord, располагается в отдельных секциях. При этом каждая секция содержит определенный набор элементов – текст, таблица, изображение, ссылка и т.д. Элементы – же в свою очередь, так же могут быть сложными и включать в себя некий набор вложенных элементов, к примеру таблицы.
Поэтому, вызывая на исполнение метод getSections(), мы получаем доступ к секциям документа, при этом в качестве результата будет возвращен массив, а значит мы его можем обойти циклом foreach().
Бесплатный курс по PHP программированию
Освойте курс и узнайте, как создать веб-приложение на PHP с полного нуля
При этом в коде цикла, для каждой секции, получим массив входящих элементов, вызывая на исполнение метод getElements(). Так как возвращаемое значение – это массив, значит, используя выше указанный цикл, мы можем получить доступ к каждой его ячейке.
При этом в переменной $e на каждой итерации цикла, содержится объект одного из элементов массива секций. Казалось бы, мы сразу можем получить текстовые данные MS Word, но для начала нужно проверить, что содержится в переменной $e.
Если в данной переменной содержится объект класса ‘PhpOffice\PhpWord\Element\TextRun’, значит мы работаем с сложной текстовой областью, в которой располагается несколько более простых элементов. Поэтому повторно вызываем метод getElements() и по результату проходимся в цикле foreach().
Таким образом, для текущего документа, в переменную $text, попадает объект элемента Text, то есть элемент простейшего текст, для получения которого достаточно вызвать на исполнение метод getText(). Для получения информации о форматировании текущего элемента, необходимо обратиться к методу getFontStyle(), который вернет объект в закрытых свойствах которого содержится указанная информация. Соответственно для доступа к значениям этих свойств необходимо использовать специальные методы:
getSize() – размер шрифта;
isBold() — возвращает истину, если используется полужирный шрифт;
getColor() – цвет текста;
getName() – имя шрифта.
Все содержимое документа, записывается в переменную $body, значение которой будет отображено на экране, используя шаблон. Пустые строки документа представляют собой объект элемента TextBreak, который можно обработать следующим образом:
Для обработки таблиц, придется добавить достаточно много строк кода, потому как таблица – это сложный элемент Table, который состоит из отдельных строк, а те в свою очередь из отдельных ячеек. И более того, каждая ячейка, может содержать еще вложенные элементы, потому как, к примеру в одной ячейке так же можно сформировать таблицу. Ниже приведу весь код, вместе с кодом обработки таблиц.
Для получения строк, необходимо вызвать метод getRows(), при этом в качестве результата будет возвращен массив объектов с информацией по каждой строке (элемент Row). Используя foreach(), обходим данный массив и для каждой строки получаем ячейки, при помощи метода getCells(). При этом опять же возвращается массив, который все так же мы обходим циклом. А далее для каждой ячейки вызываем на исполнение метод getElements(), для получения ее элементов. И так далее по принципу описанным выше.
Далее, осталось только отобразить значение переменной $body, любым удобным для Вас способом.
На этом данный урок я буду завершать. Как Вы видите, PHPWord предоставляет достаточно мощные инструменты по работе с документами MS Word, но и в тоже время сложные в плане получения данных из объектов.
От автора: не так давно на нашем сайте были опубликованы уроки по работе с таблицами Microsoft Excel средствами языка PHP, которые вызвали значительный интерес у нашей аудитории и поэтому, сегодня я решил показать Вам, как создавать документы Microsoft Word ,формата .docx, используя мощнейшую библиотеку PHPWord.
Актуальную версию библиотеки PHPWord, вы найдете на сервисе GitHub.
Бесплатный курс по PHP программированию
Освойте курс и узнайте, как создать веб-приложение на PHP с полного нуля
На данной странице, приведено краткое описание и инструкция по установке библиотеки. Но данная инструкция очень ограничена и не описывает всех возможностей библиотеки, поэтому, официальную PHPWord документацию, для разработчиков, Вы найдете по ссылке.
Paperclip-Systems commented May 18, 2017
I don't know if the problem I was having was the same as this but this fixed the problem for me
jacklove2run commented Mar 28, 2018
I also have this problem. Using IOFactory to load a .docx file and wanted to save it into type of html, but lost all the images. Dose this problem solved?
If you use the developer version of PHPWord, it solves it partially , for me still not acceptable. Unfortunately I have no time to take a look on the code to find the bug . I had to change to another library temporally.
On Mar 28, 2018, at 8:28 AM, jacklove2run ***@***.***> wrote: I also have this problem. Using IOFactory to load a .docx file and wanted to save it into type of html, but lost all the images. Dose this problem solved? — You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub , or mute the thread .
troosan commented Dec 19, 2017
@Piuliss @kichetof please try with the dev-develop, parsing of docx document has been improved.
jacklove2run commented Mar 28, 2018
@Piuliss OK thanks i'll try developer version later but can u tell me what library u are using now?
Piuliss commented Dec 20, 2017
should I link to develop repo to composer?
because
composer require phpoffice/phpword:dev-develop
it is not working
ammarax commented May 15, 2020
No one fixed this?? is possible that nobody create an exporter from 2017 to 2020 from word to PDF starting from template object??
Paperclip-Systems commented May 18, 2017
I don't know if the problem I was having was the same as this but this fixed the problem for me
Piuliss commented Dec 27, 2017
@troosan finally I could install dev-develop version. Well, now styles look much better, but still are not perfect. Specially with margin and font sizes. I will take look in the code if I can fix it. Thanks.
Читайте также: