I have problem that showing the content or docx
file in php(laravel 5)
.
I did not find any solution to show the content. I use phpword
lib for reading, I read the document of phpword but not find the solution.
Here is my code:
+upload in html:
<form method="post" action="doc/upload" enctype="multipart/form-data">
{{csrf_field()}}
<input type="file" name="file" accept=".doc, .docx"/>
<button class="btn btn-primary" style="margin-top: 5px"><span class="glyphicon glyphicon-import" aria-hidden="true"></span> Upload</button>
</form>
+ process:
public function upload(Request $request){
$file = $request->file('file');
$phpWord = \PhpOffice\PhpWord\IOFactory::load($file);
//i use this line below for showing but it can not show exactly
$phpWord->save('php://output');
}
If you want to show all word doc contetns, then the best way would be to save the word file as html and then show html contents in an Iframe.
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'HTML');
$objWriter->save('doc.html');
if you want to grab just the plain text contents from the doc, you might try something like this
foreach($phpWord->getSections() as $section) {
foreach($section->getElements() as $element) {
if(method_exists($element,'getText')) {
echo($element->getText() . "<br>");
}
}
}
Hope this helps.
I was also looking for the answer for this and here's my code to read a docx file using PHPWord. I'm completing the steps from installation (this is for laravel 5)
Step 1. add https://github.com/PHPOffice/PHPWord in your composer file. (composer.json)
"require": {
"phpoffice/phpword": "v0.13.*"
}
Step 2. Add to your controller the IOFactory.
use PhpOffice\PhpWord\IOFactory;
Step 3. create a reader and load the file.
$phpWord = IOFactory::createReader('Word2007')->load($request->file('file')->path());
Step 4. You can already check the $phpWord for properties and contents of the document.
Step 5. If you want to extract the contents of document. use code below
$phpWord = IOFactory::createReader('Word2007')->load($request->file('file')->path());
foreach($phpWord->getSections() as $section) {
foreach($section->getElements() as $element) {
if(method_exists($element,'getText')) {
echo($element->getText() . "<br>");
}
}
}