I have a laravel app, version 5.39. I'm using phpoffice/phpword 0.15 library.
I'm trying to upload a .docx file and read its content.
I tried this:
$phpWord = IOFactory::createReader('Word2007')->load($request->file('file')->path());
$text = '';
foreach($phpWord->getSections() as $section) {
foreach($section->getElements() as $element) {
if(method_exists($element,'getText')) {
$text = $text . $element->getText();
}
}
}
Log::info($text);
But it logs an empty string, no errors.
I also tried this, but the result is the same:
$file = $request->file('file');
$fileName = $file->getClientOriginalName();
$newFileName = time() . '_' . str_replace(' ', '_', $fileName);
$filePath = $file->storeAs('app', $newFileName);
$realPath = Storage::path($filePath);
$reader = IOFactory::createReader('Word2007');
$phpWord = $reader->load($realPath);
$text = '';
$sections = $phpWord->getSections();
foreach ($sections as $section) {
$elements = $section->getElements();
foreach ($elements as $element) {
$text .= $element->getText();
}
}
Log::info($text);
My html file looks like this
<form id="file-upload-form" method="post" enctype="multipart/form-data">
@csrf
<input type="file" name="file">
<button type="submit" id="submit-button">Upload and read Word file</button>
</form>
<script>
$(function() {
$('#file-upload-form').on('submit', function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: "/upload-file",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(data) {
console.log(data);
// Update the page with the text from the Word file
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
// Handle the error
}
});
});
});
<script>
Is there a way to read the content of the file?