TRY AND ERROR

気になったこと、勉強したこと、その他雑記など色々メモしていきます。。Sometimes these posts will be written in English.,

今更ながらphpでword(docx)を読み込んでplain textを得る

word(docx)ファイルを出力する、とかのサンプルやライブラリは結構あるんですが、
今回はそもそもただ単に中身のプレーンテキストが欲しいという場合の話。

docx(確かword2007以降)は実はzipアーカイブなので、unzipとかで解凍できる。
その中にword/document.xmlというのがあって、それにテキストの情報が入っている。
これをパースしてパラグラフ -> テキストで回せば改行含めプレーンテキストとして取得できます。

今回はPHPのZipArchiveでパースしますが、別にphpでなくても全然大丈夫です。
PHP: ZipArchive - Manual

$NL = "\n";
$contents = "";
$file_path = "your.docx";
$zip = new \ZipArchive();

if ($zip->open($file_path) === true) {
	$xml = $zip->getFromName("word/document.xml");
	if ($xml) {
		$dom = new \DOMDocument();
		$dom->loadXML($xml);
		$paragraphs = $dom->getElementsByTagName("p");
		foreach ($paragraphs as $p) {
			$texts = $p->getElementsByTagName("t");
			foreach ($texts as $t) {
				$contents .= $t->nodeValue;
			}
                        // Add New Line after a paragraph.
			$contents .= $NL;
		}
	}
}
return $contents;
English sub


Although There are many samples and libraries on the web, this post is about that simple way you can get the plain text from docx file.
docx file is essentially zip archive that consists some rels, So we could unzip it.
there is a xml file named document.xml in the rels which has information of text.
We could fetch plain text by parsing xml and iterating its specific node which are like paragraph or text,,