Last active
November 19, 2020 11:36
-
-
Save Anexo/106c25dc4a99843936562ab71c5eef18 to your computer and use it in GitHub Desktop.
Read in a docx, save into variable and count the words. Word 2007 format only.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require 'vendor/autoload.php'; | |
$source = 'example.docx'; | |
$phpword = \PhpOffice\PhpWord\IOFactory::load($source); | |
$sections = $phpword->getSections(); | |
$uploadedText = ''; | |
foreach ($sections as $section) { | |
$elements = $section->getElements(); | |
foreach ($elements as $element) { | |
if (get_class($element) === 'PhpOffice\PhpWord\Element\Text') { | |
$uploadedText .= $element->getText(); | |
$uploadedText .= ' '; | |
} else if (get_class($element) === 'PhpOffice\PhpWord\Element\TextRun') { | |
$textRunElements = $element->getElements(); | |
foreach ($textRunElements as $textRunElement) { | |
$uploadedText .= $textRunElement->getText(); | |
$uploadedText .= ' '; | |
} | |
} else if (get_class($element) === 'PhpOffice\PhpWord\Element\TextBreak') { | |
$uploadedText .= ' '; | |
} else { | |
throw new Exception('Unknown class type ' . get_class($e)); | |
} | |
} | |
} | |
$uploadedText = str_replace(' ',"", $uploadedText); | |
$uploadedText = str_replace('•',"",$uploadedText); | |
$uploadedText = preg_split('/\s+/', $uploadedText); | |
$numberWords = count($uploadedText); |
Excellent code try to define $uploadedText=''; somewhere around line 10
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
very good
thanks