使用PHP读取和创建txt,doc,xls,pdf类型文件
PHP读取或者创建txt,doc,xls,pdf各个类型文件的方法.
php读取(文本.txt)文件:
一般是使用fopen、fgets的方法,例如:
|
1
2
3
4
5
6
7
8
9
10
11
|
$fp=fopen('文件名.txt','r'); for ($i=1;$i<100;$i++) fgets($fp);//跳过前99行 $arr=array();//初始化数组 for ($i=0;$i<100;$i++) $arr[]=fgets($fp);//读出100~200行 fclose($fp); //下面输出内容 echo '<table>'; for ($i=0;$i<50;$i++){ echo '<Tr><td>'.$arr[$i].'<td>'.$arr[$i+50]; } echo '</table>'; |
以上是如何用php读取txt文件的第n到第n+100行,并输出。
读取第100到第200行,然后用50行2列的表格输出。
php读取(word .doc)文件:
|
1
2
3
4
5
6
7
8
|
header(Content-type:application/msword); $fp=fopen("xxx.doc",r); $file=file($fp); foreach($file as $k=>;$v){ echo $v; |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
$word = new COM("word.application") or die("无法定位WORD安装路径!"); print "加载WORD( 版本: )成功,已经保存在您的硬盘上了。n"; php程序员站 //将其置前 $word->Visible = 1; php程序员站 //打开一个空文档 $word->Documents->Add(); //随便做些事情 $word->Selection->TypeText("这是一个在PHP中调用COM的测试。"); //$word->Selection->TypeText("This is a test.。"); phperz.com $word->Documents[1]->SaveAs("test.doc"); //关闭 word $word->Quit(); //释放对象 $word->Release(); $word = null; |
php读取(Excel.xls)文件(csv文件):
首先把xls转化为csv格式的,然后使用下面方法读取csv格式文件就可以了。
|
1
2
3
4
5
6
7
8
9
10
11
12
|
header("Content-type:html/txt"); $row = 1; $handle = fopen("jxw-501-600.csv","r"); while ($data = fgetcsv($handle, 1000, ",")) { $num = count($data); echo "<p> $num fields in line $row: <br>\n"; $row++; for ($c=0; $c < $num; $c++) { echo $data[$c] . "<br>\n"; } } fclose($handle); |
使用表单上传word文件到数据库 然后打开数据库的word。
第二种 是把word 转换为PDF 用world转换工具 ,然后在吧PDF 导入到页面上
php读取pdf文件
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
// 创建一个新的pdf文档句柄 $pdf = pdf_new(); // 打开一个文件 pdf_open_file($pdf, "pdftest.pdf"); // 开始一个新页面(a4) pdf_begin_page($pdf, 595, 842); // 得到并使用字体对象 $arial = pdf_findfont($pdf, "arial", "host", 1); pdf_setfont($pdf, $arial, 10); www.phperz.com // 输出文字 php程序员站 pdf_show_xy($pdf, "this is an exam of pdf documents, it is a good lib,",50, 750); pdf_show_xy($pdf, "if you like,please try yourself!", 50, 730); // 结束一页 pdf_end_page($pdf); // 关闭并保存文件 pdf_close($pdf); |