docまたはdocxの内容を読み取る方法を知りたいのですが。Linux VPSとPHPを使用していますが、他の言語を使用したより簡単な解決策がある場合は、Linux Webサーバーで機能する限り、お知らせください。
9 に答える
これは.DOCXソリューションのみです。.DOCまたは.PDFの場合、PDFの場合はpdf2text.phpなどの他のものを使用する必要があります
function docx2text($filename) {
return readZippedXML($filename, "word/document.xml");
}
function readZippedXML($archiveFile, $dataFile) {
// Create new ZIP archive
$zip = new ZipArchive;
// Open received archive file
if (true === $zip->open($archiveFile)) {
// If done, search for the data file in the archive
if (($index = $zip->locateName($dataFile)) !== false) {
// If found, read it to the string
$data = $zip->getFromIndex($index);
// Close archive file
$zip->close();
// Load XML from a string
// Skip errors and warnings
$xml = new DOMDocument();
$xml->loadXML($data, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
// Return data without XML formatting tags
return strip_tags($xml->saveXML());
}
$zip->close();
}
// In case of failure return empty string
return "";
}
echo docx2text("test.docx"); // Save this contents to file
私の解決策は、.doc のAntiwordと .docx のdocx2txtです。
あなたが管理しているLinuxサーバーを想定して、それぞれをダウンロードし、抽出してからインストールします。私はそれぞれをシステム全体にインストールしました:
アンチワード: make global_install
docx2txt:make install
次に、これらのツールを使用して、テキストを PHP の文字列に抽出します。
//for .doc
$text = shell_exec('/usr/local/bin/antiword -w 0 ' .
escapeshellarg($docFilePath));
//for .docx
$text = shell_exec('/usr/local/bin/docx2txt.pl ' .
escapeshellarg($docxFilePath) . ' -');
docx2txt には perl が必要です
no_freedom のソリューションは docx ファイルからテキストを抽出しますが、空白を解体できます。私がテストしたほとんどのファイルには、区切るべき単語間にスペースがないインスタンスがありました。処理中の文書を全文検索したい場合には不向きです。
ApachePOIを試してください。Javaでうまく機能します。LinuxにJavaをインストールするのに問題はないと思います。
doc から txt へのコンバーター機能に少し改善を挿入します
private function read_doc() {
$line_array = array();
$fileHandle = fopen( $this->filename, "r" );
$line = @fread( $fileHandle, filesize( $this->filename ) );
$lines = explode( chr( 0x0D ), $line );
$outtext = "";
foreach ( $lines as $thisline ) {
$pos = strpos( $thisline, chr( 0x00 ) );
if ( $pos !== false ) {
} else {
$line_array[] = preg_replace( "/[^a-zA-Z0-9\s\,\.\-\n\r\t@\/\_\(\)]/", "", $thisline );
}
}
return implode("\n",$line_array);
}
これで空の行が保存され、txt ファイルは行ごとに表示されます。