-
-
Save bobbyaxe74/be4feea43d89f4ad6003a12a5faf2bdd 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 | |
function CountWords($source, $source_extension) | |
{ | |
//add supported formarts to array | |
$supported_extensions = array('docx','doc'); | |
if (in_array($source_extension, $supported_extensions)){ | |
\PhpOffice\PhpWord\Settings::setOutputEscapingEnabled(true); | |
$phpword = \PhpOffice\PhpWord\IOFactory::load($source); | |
//according to documentation hiding spelling and grammatical errors can improve speed | |
$phpword->getSettings()->setHideGrammaticalErrors(true); | |
$phpword->getSettings()->setHideSpellingErrors(true); | |
$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); | |
return $numberWords; | |
} | |
else{ | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment