PHP读取doc,docx,xls,pdf,txt内容

   2016-12-23 0
核心提示:我的一个客户有这样的需求:上传文件,可以是doc,docx,xls,pdf,txt格式,现需要用php读取这些文件的内容,然后计算文件里面字数.1.PHP读取DOC格式的文件 PHP没有自带读取word文件的类,或者是库,这里我们使用 antiword ( http://www.winfield.demon.nl/ )这个包来

我的一个客户有这样的需求:上传文件,可以是doc,docx,xls,pdf,txt格式,现需要用php读取这些文件的内容,然后计算文件里面字数.

1.PHP读取DOC格式的文件

PHP没有自带读取word文件的类,或者是库,这里我们使用 antiword ( http://www.winfield.demon.nl/ )这个包来读取doc文件.

首先介绍一下如何在windows下使用:

1.打开 http://www.winfield.demon.nl/ (antiword下载页面),找到对应的windows版本( http://www.winfield.demon.nl/#Windows ),下载 antiword windows版本 ( antiword-0_37-windows.zip );

2.将下载下来的文件解压到C盘根目录下;

这里还有一点需要注意的: http://www.informatik.uni-frankfurt.de/~markus/antiword/00README.WIN 这个连接里有windows下安装的说明文件.

需要设置环境变量,我的电脑(右键)->高级->环境变量->在上面的用户变量里新建一个

变量名:HOME

变量值:c:\home这个目录应该是存在的,如果不存在就在C盘下创建一个home文件夹.

然后在系统变量,修改Path,在Path变量的值最前面加上%HOME%\antiword.

PHP读取doc,docx,xls,pdf,txt内容

3.开始->运行->CMD 进入到antiword目录;

输入 antiword -h 看看效果.

PHP读取doc,docx,xls,pdf,txt内容

4.然后我们使用antiword –t 命令读取一下doc文件内容;首先复制一个doc文件到c:\antiword目录,然后执行

>antiword –t 文件名.doc

就可以看到屏幕上输出word文件的内容了.

可能你会问了,这和PHP读取word有什么关系呢?呵呵,别急,我们来看看如何在PHP里使用这个命令.

<?php

$file = “D:\xampp\htdocs\word_count\uploads\doc-english.doc”;

$content = shell_exec(“c:\antiword\antiword –f $file”);

?>

这样就把word里面的内容读取content里面了.

至于如何在Linux下读取doc文件内容,就是下载linux版本的压缩包,里面有readme.txt文件,按照那种方式安装就可以了.

$content = shell_exec ( "/usr/local/bin/antiword -f $file" );

2.PHP读取PDF文件内容

php也没有专门用来读取pdf内容的类库.这样我们采用第三方包( xpdf ).还是先做windows下的操作,下载,将其解压到C盘根目录下.

开始->运行->cmd->cd /d c:\xpdf

<?php

$file = “D:\xampp\htdocs\word_count\uploads\pdf-english.pdf”;

$content = shell_exec ( "c:\\xpdf\\pdftotext $file -" );

?>

这样就可以把pdf文件的内容读取到php变量里了.

Linux下的安装方法也很简单这里就不在一一列出

<?php

$content = shell_exec ( "/usr/bin/pdftotext $file -" );

?>

3.PHP读取ZIP文件内容

首先使用PHP zip解压zip文件,然后读取解压包里的文件,如果是word就采用antiword读取,如果是pdf就使用xpdf读取.

<?php

/**

* Read ZIP valid file 

* @param string $file file path 

* @return string total valid content 

*/ 

function ReadZIPFile($file = '') { 

$content = ""; 

$inValidFileName = array (); 

$zip = new ZipArchive ( ); 

if ($zip->open ( $file ) === TR ) { 

for($i = 0; $i < $zip->numFiles; $i ++) { 

$entry = $zip->getNameIndex ( $i ); 

if (preg_match ( '#\.(txt)|\.(doc)|\.(docx)|\.(pdf)$#i', $entry )) { 

$zip->extractTo ( pathinfo ( $file, PATHINFO_DIRNAME ) . "/" . pathinfo ( $file, PATHINFO_FILENAME ), array ( 

$entry 

) ); 

$content .= CheckSystemOS ( pathinfo ( $file, PATHINFO_DIRNAME ) . "/" . pathinfo ( $file, PATHINFO_FILENAME ) . "/" . $entry ); 

} else { 

$inValidFileName [$i] = $entry; 

$zip->close (); 

rrmdir ( pathinfo ( $file, PATHINFO_DIRNAME ) . "/" . pathinfo ( $file, PATHINFO_FILENAME ) ); 

/*if (file_exists ( $file )) { 

unlink ( $file ); 

}*/ 

return $content; 

} else { 

return ""; 

}

?>

4.PHP读取DOCX文件内容

docx文件其实是由很多XML文件组成,其中内容就存在于word/document.xml里面.

我们找到一个docx文件,使用zip文件打开(或者把docx后缀名改为zip,然后解压)

PHP读取doc,docx,xls,pdf,txt内容

在word目录下有document.xml

PHP读取doc,docx,xls,pdf,txt内容

docx文件的内容就存在于document.xml里面,我们读取这个文件就可以了.

<?php

/**

* Read Docx File 

* @param string $file filepath 

* @return string file content 

*/ 

function parseWord($file) { 

$content = ""; 

$zip = new ZipArchive ( ); 

if ($zip->open ( $file ) === tr ) { 

for($i = 0; $i < $zip->numFiles; $i ++) { 

$entry = $zip->getNameIndex ( $i ); 

if (pathinfo ( $entry, PATHINFO_BASENAME ) == "document.xml") { 

$zip->extractTo ( pathinfo ( $file, PATHINFO_DIRNAME ) . "/" . pathinfo ( $file, PATHINFO_FILENAME ), array ( 

$entry 

) ); 

$filepath = pathinfo ( $file, PATHINFO_DIRNAME ) . "/" . pathinfo ( $file, PATHINFO_FILENAME ) . "/" . $entry; 

$content = strip_tags ( file_get_contents ( $filepath ) ); 

break; 

$zip->close (); 

rrmdir ( pathinfo ( $file, PATHINFO_DIRNAME ) . "/" . pathinfo ( $file, PATHINFO_FILENAME ) ); 

return $content; 

} else { 

return ""; 

}

?>

如果想要通过PHP创建docx文件,或者是把docx文件转为xhtml,pdf可以使用phpdocx,( http://www.phpdocx.com/ )

PHP读取doc,docx,xls,pdf,txt内容

5.PHP读TXT

直接使用PHP file_get_content函数就可以了.

<?php

$file = “D:\xampp\htdocs\word_count\uploads\eng.txt”;

$content = file_get_content($file);

?>

6.PHP读EXCEL

http://phpexcel.codeplex.com/

现在只是读取文件内容了,怎么计算单词的个数呢?

PHP有一个自带的函数,str_word_count,这个函数可以计算出单词的个数,但是如果要计算antiword读取出来的doc文件的单词个数就会很大的误差.

这里我们使用以下这个函数专门用来读取单词个数

<?php

/**

* statistic word count 

* @param string $content word content of the file 

* @return int word count of the content 

*/ 

function StatisticWordsCount($text = '') { 

//    $text = trim ( preg_replace ( '/\d+/', ' ', $text ) ); // remove extra spaces 

$text = str_replace ( str_split ( '|' ), '', $text ); // remove these chars (you can specify more) 

//    $text = str_replace ( str_split ( '-' ), '', $text ); // remove these chars (you can specify more) 

$text = trim ( preg_replace ( '/\s+/', ' ', $text ) ); // remove extra spaces 

$text = preg_replace ( '/-{2,}/', '', $text ); // remove 2 or more dashes in a row 

$len = strlen ( $text ); 

if (0 === $len) { 

return 0; 

$words = 1; 

while ( $len -- ) { 

if (' ' === $text [$len]) { 

++ $words; 

return $words; 

}

?>

详细的代码如下:

<?php

/** 

* check system operation win or linux 

* @param string $file contain file path and file name 

* @return file content 

*/ 

function CheckSystemOS($file = '') { 

$content = ""; 

//    $type = s str ( $file, strrpos ( $file, '.' ) + 1 ); 

$type = pathinfo ( $file, PATHINFO_EXTENSION ); 

//    global $UNIX_ANTIWORD_PATH, $UNIX_XPDF_PATH; 

if (strtoupper ( s str ( PHP_OS, 0, 3 ) ) === 'WIN') { //this is a server using windows 

switch (strtolower ( $type )) { 

case 'doc' : 

$content = shell_exec ( "c:\\antiword\\antiword -f $file" ); 

break; 

case 'docx' : 

$content = parseWord ( $file ); 

break; 

case 'pdf' : 

$content = shell_exec ( "c:\\xpdf\\pdftotext $file -" ); 

break; 

case 'zip' : 

$content = ReadZIPFile ( $file ); 

break; 

case 'txt' : 

$content = file_get_contents ( $file ); 

break; 

} else { //this is a server not using windows 

switch (strtolower ( $type )) { 

case 'doc' : 

$content = shell_exec ( "/usr/local/bin/antiword -f $file" ); 

break; 

case 'docx' : 

$content = parseWord ( $file ); 

break; 

case 'pdf' : 

$content = shell_exec ( "/usr/bin/pdftotext $file -" ); 

break; 

case 'zip' : 

$content = ReadZIPFile ( $file ); 

break; 

case 'txt' : 

$content = file_get_contents ( $file ); 

break; 

/*if (file_exists ( $file )) { 

@unlink ( $file ); 

}*/ 

return $content; 

}

/**

* statistic word count 

* @param string $content word content of the file 

* @return int word count of the content 

*/ 

function StatisticWordsCount($text = '') { 

//    $text = trim ( preg_replace ( '/\d+/', ' ', $text ) ); // remove extra spaces 

$text = str_replace ( str_split ( '|' ), '', $text ); // remove these chars (you can specify more) 

//    $text = str_replace ( str_split ( '-' ), '', $text ); // remove these chars (you can specify more) 

$text = trim ( preg_replace ( '/\s+/', ' ', $text ) ); // remove extra spaces 

$text = preg_replace ( '/-{2,}/', '', $text ); // remove 2 or more dashes in a row 

$len = strlen ( $text ); 

if (0 === $len) { 

return 0; 

$words = 1; 

while ( $len -- ) { 

if (' ' === $text [$len]) { 

++ $words; 

return $words; 

}

/**

* Read Docx File 

* @param string $file filepath 

* @return string file content 

*/ 

function parseWord($file) { 

$content = ""; 

$zip = new ZipArchive ( ); 

if ($zip->open ( $file ) === tr ) { 

for($i = 0; $i < $zip->numFiles; $i ++) { 

$entry = $zip->getNameIndex ( $i ); 

if (pathinfo ( $entry, PATHINFO_BASENAME ) == "document.xml") { 

$zip->extractTo ( pathinfo ( $file, PATHINFO_DIRNAME ) . "/" . pathinfo ( $file, PATHINFO_FILENAME ), array ( 

$entry 

) ); 

$filepath = pathinfo ( $file, PATHINFO_DIRNAME ) . "/" . pathinfo ( $file, PATHINFO_FILENAME ) . "/" . $entry; 

$content = strip_tags ( file_get_contents ( $filepath ) ); 

break; 

$zip->close (); 

rrmdir ( pathinfo ( $file, PATHINFO_DIRNAME ) . "/" . pathinfo ( $file, PATHINFO_FILENAME ) ); 

return $content; 

} else { 

return ""; 

}

/**

* Read ZIP valid file 

* @param string $file file path 

* @return string total valid content 

*/ 

function ReadZIPFile($file = '') { 

$content = ""; 

$inValidFileName = array (); 

$zip = new ZipArchive ( ); 

if ($zip->open ( $file ) === TR ) { 

for($i = 0; $i < $zip->numFiles; $i ++) { 

$entry = $zip->getNameIndex ( $i ); 

if (preg_match ( '#\.(txt)|\.(doc)|\.(docx)|\.(pdf)$#i', $entry )) { 

$zip->extractTo ( pathinfo ( $file, PATHINFO_DIRNAME ) . "/" . pathinfo ( $file, PATHINFO_FILENAME ), array ( 

$entry 

) ); 

$content .= CheckSystemOS ( pathinfo ( $file, PATHINFO_DIRNAME ) . "/" . pathinfo ( $file, PATHINFO_FILENAME ) . "/" . $entry ); 

} else { 

$inValidFileName [$i] = $entry; 

$zip->close (); 

rrmdir ( pathinfo ( $file, PATHINFO_DIRNAME ) . "/" . pathinfo ( $file, PATHINFO_FILENAME ) ); 

/*if (file_exists ( $file )) { 

unlink ( $file ); 

}*/ 

return $content; 

} else { 

return ""; 

}

/**

* remove directory 

* @param string $dir path dir 

*/ 

function rrmdir($dir) { 

if (is_dir ( $dir )) { 

$objects = scandir ( $dir ); 

foreach ( $objects as $object ) { 

if ($object != "." && $object != "..") { 

if (filetype ( $dir . "/" . $object ) == "dir") { 

rrmdir ( $dir . "/" . $object ); 

} else { 

unlink ( $dir . "/" . $object ); 

reset ( $objects ); 

rmdir ( $dir ); 

}

//调用方法

$file = “D:\xampp\htdocs\word_count\uploads\pdf-german.zip”;

$word_number = StatisticWordsCount ( CheckSystemOS ( $file) );

?>

http://www.it300.com/article-15290.html

 
标签: PHP
反对 0举报 0 评论 0
 

免责声明:本文仅代表作者个人观点,与乐学笔记(本网)无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
    本网站有部分内容均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,若因作品内容、知识产权、版权和其他问题,请及时提供相关证明等材料并与我们留言联系,本网站将在规定时间内给予删除等相关处理.

  • php-fpm进程管理的三种模式 phpfpm子进程
    php-fpm进程管理的三种模式 phpfpm子进程
    php-fpm解读-进程管理的三种模式—程序媛大丽标明转载以示尊重 感谢原作者的分享。php-fpm进程管理一共有三种模式:ondemand、static、dynamic,我们可以在同一个fpm的master配置三种模式,看下图1。php-fpm的工作模式和nginx类似,都是一个master,多个worke
    03-08
  • nginx和php-fpm 是使用 tcp socket 还是 unix s
    tcp socket允许通过网络进程之间的通信,也可以通过loopback进行本地进程之间通信。unix socket允许在本地运行的进程之间进行通信。分析从上面的图片可以看,unix socket减少了不必要的tcp开销,而tcp需要经过loopback,还要申请临时端口和tcp相关资源。但是
    03-08
  • [PHP8] 我参加了PHP8工程师认证初学者考试beta考试
    [PHP8] 我参加了PHP8工程师认证初学者考试beta
    前几天,2022/08/05,PHP工程师认证机构PHP8 技术员认证初级考试宣布实施考试将于 2023 年春季开始。和 beta 测试完成于 2022/09/11所以我收到了。一般社团法人BOSS-CON JAPAN(代表理事:Tadashi Yoshimasa,地点:东京都世田谷区,以下简称“BOSS-CON JAPAN
    03-08
  • 将 PHP Insights 放入旧版 PJ 不是很好吗?谈论
    将 PHP Insights 放入旧版 PJ 不是很好吗?谈论
    介绍在最近的PHP系统开发中,感觉故事在理所当然包含静态分析工具的前提下进行。我的周围现有代码很脏,我很久以前安装了工具,但几乎没有检查已经观察到许多这样的案例。 (这是小说。而不是像 0 或 100 这样不允许单行错误的静态分析,一点一点,逐渐我想介
    03-08
  • PHP基于elasticsearch全文搜索引擎的开发 php使
    1.概述:全文搜索属于最常见的需求,开源的 Elasticsearch (以下简称 Elastic)是目前全文搜索引擎的首选。Elastic 的底层是开源库 Lucene。但是,你没法直接用 Lucene,必须自己写代码去调用它的接口。Elastic 是 Lucene 的封装,提供了 REST API 的操作接
    02-09
  • php视图操作
    一、视图的基本介绍         视图是虚拟的表。与包含数据的表不一样,视图只包含使用时动态检索数据的查询。        使用视图需要MySQL5及以后的版本支持。        下面是视图的一些常见应用:        重用SQL语句;        简化复杂的S
    02-09
  • php中图像处理的常用函数 php图形图像处理技术
    php中图像处理的常用函数 php图形图像处理技术
    1.imagecreate()函数imagecreate()函数是基于一个调色板的画布。?php $im = imagecreate(200,80);                //创建一个宽200,高80的画布。$white = imagecolorallocate($im,225,35,180);     //设置画布的背景颜色imagegif($im);
    02-09
  • PHP安全之webshell和后门检测
    PHP安全之webshell和后门检测
    基于PHP的应用面临着各种各样的攻击:XSS:对PHP的Web应用而言,跨站脚本是一个易受攻击的点。攻击者可以利用它盗取用户信息。你可以配置Apache,或是写更安全的PHP代码(验证所有用户输入)来防范XSS攻击SQL注入:这是PHP应用中,数据库层的易受攻击点。防范
    02-09
  • php使用时间戳保存时间的意义 PHP获取时间戳
    时间戳记录的是格林尼治时间,使用date格式化的时候会根据你程序设置的不同时区显示不同的时间。如果使用具体时间,则还需要进行多一步转换。
    02-09
  • PHP 获取提交表单数据方法
    PHP $_GET 和 $_POST变量是用来获取表单中的信息的,比如用户输入的信息。PHP表单操作在我们处理HTML表单和PHP表单时,我们要记住的重要一点是:HTML页面中的任何一个表单元素都可以自动的用于PHP脚本:表单举例: htmlbodyform action="welcome.php" method
    02-09
点击排行