php示例代码之读取文件(php读取文件的函数)

本文目录一览:

如何利用php读取txt文件再将数据插入到数据库

serial_number.txt的示例内容:

serial_number.txt:

DM00001A11 0116,

SN00002A11 0116,

AB00003A11 0116,

PV00004A11 0116,

OC00005A11 0116,

IX00006A11 0116,

创建数据表:

create table serial_number(

id int primary key auto_increment not null,

serial_number varchar(50) not null

)ENGINE=InnoDB DEFAULT CHARSET=utf8;

php代码如下:

$conn = mysql_connect(‘127.0.0.1′,’root’,”) or die(“Invalid query: ” . mysql_error());

mysql_select_db(‘test’, $conn) or die(“Invalid query: ” . mysql_error());

$content = file_get_contents(“serial_number.txt”);

$contents= explode(“,”,$content);//explode()函数以”,”为标识符进行拆分

foreach ($contents as $k = $v)//遍历循环

{

$id = $k;

$serial_number = $v;

mysql_query(“insert into serial_number (`id`,`serial_number`)

VALUES(‘$id’,’$serial_number’)”);

}

备注:方法有很多种,我这里是在拆分txt文件为数组后,然后遍历循环得到的数组,每循环一次,往数据库中插入一次。

再给大家分享一个支持大文件导入的

?php

/**

* $splitChar 字段分隔符

* $file 数据文件文件名

* $table 数据库表名

* $conn 数据库连接

* $fields 数据对应的列名

* $insertType 插入操作类型,包括INSERT,REPLACE

*/

function loadTxtDataIntoDatabase($splitChar,$file,$table,$conn,$fields=array(),$insertType=’INSERT’){

if(empty($fields)) $head = “{$insertType} INTO `{$table}` VALUES(‘”;

else $head = “{$insertType} INTO `{$table}`(`”.implode(‘`,`’,$fields).”`) VALUES(‘”; //数据头

$end = “‘)”;

$sqldata = trim(file_get_contents($file));

if(preg_replace(‘/\s*/i’,”,$splitChar) == ”) {

$splitChar = ‘/(\w+)(\s+)/i’;

$replace = “$1′,'”;

$specialFunc = ‘preg_replace’;

}else {

$splitChar = $splitChar;

$replace = “‘,'”;

$specialFunc = ‘str_replace’;

}

//处理数据体,二者顺序不可换,否则空格或Tab分隔符时出错

$sqldata = preg_replace(‘/(\s*)(\n+)(\s*)/i’,’\’),(\”,$sqldata); //替换换行

$sqldata = $specialFunc($splitChar,$replace,$sqldata); //替换分隔符

$query = $head.$sqldata.$end; //数据拼接

if(mysql_query($query,$conn)) return array(true);

else {

return array(false,mysql_error($conn),mysql_errno($conn));

}

}

//调用示例1

require ‘db.php’;

$splitChar = ‘|’; //竖线

$file = ‘sqldata1.txt’;

$fields = array(‘id’,’parentid’,’name’);

$table = ‘cengji’;

$result = loadTxtDataIntoDatabase($splitChar,$file,$table,$conn,$fields);

if (array_shift($result)){

echo ‘Success!br/’;

}else {

echo ‘Failed!–Error:’.array_shift($result).’br/’;

}

/*sqlda ta1.txt

1|0|A

2|1|B

3|1|C

4|2|D

— cengji

CREATE TABLE `cengji` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`parentid` int(11) NOT NULL,

`name` varchar(255) DEFAULT NULL,

PRIMARY KEY (`id`),

UNIQUE KEY `parentid_name_unique` (`parentid`,`name`) USING BTREE

) ENGINE=InnoDB AUTO_INCREMENT=1602 DEFAULT CHARSET=utf8

*/

//调用示例2

require ‘db.php’;

$splitChar = ‘ ‘; //空格

$file = ‘sqldata2.txt’;

$fields = array(‘id’,’make’,’model’,’year’);

$table = ‘cars’;

$result = loadTxtDataIntoDatabase($splitChar,$file,$table,$conn,$fields);

if (array_shift($result)){

echo ‘Success!br/’;

}else {

echo ‘Failed!–Error:’.array_shift($result).’br/’;

}

/* sqldata2.txt

11 Aston DB19 2009

12 Aston DB29 2009

13 Aston DB39 2009

— cars

CREATE TABLE `cars` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`make` varchar(16) NOT NULL,

`model` varchar(16) DEFAULT NULL,

`year` varchar(16) DEFAULT NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8

*/

//调用示例3

require ‘db.php’;

$splitChar = ‘ ‘; //Tab

$file = ‘sqldata3.txt’;

$fields = array(‘id’,’make’,’model’,’year’);

$table = ‘cars’;

$insertType = ‘REPLACE’;

$result = loadTxtDataIntoDatabase($splitChar,$file,$table,$conn,$fields,$insertType);

if (array_shift($result)){

echo ‘Success!br/’;

}else {

echo ‘Failed!–Error:’.array_shift($result).’br/’;

}

/* sqldata3.txt

11 Aston DB19 2009

12 Aston DB29 2009

13 Aston DB39 2009

*/

//调用示例3

require ‘db.php’;

$splitChar = ‘ ‘; //Tab

$file = ‘sqldata3.txt’;

$fields = array(‘id’,’value’);

$table = ‘notExist’; //不存在表

$result = loadTxtDataIntoDatabase($splitChar,$file,$table,$conn,$fields);

if (array_shift($result)){

echo ‘Success!br/’;

}else {

echo ‘Failed!–Error:’.array_shift($result).’br/’;

}

//附:db.php

/* //注释这一行可全部释放

?

?php

static $connect = null;

static $table = ‘jilian’;

if(!isset($connect)) {

$connect = mysql_connect(“localhost”,”root”,””);

if(!$connect) {

$connect = mysql_connect(“localhost”,”Zjmainstay”,””);

}

if(!$connect) {

die(‘Can not connect to database.Fatal error handle by /test/db.php’);

}

mysql_select_db(“test”,$connect);

mysql_query(“SET NAMES utf8”,$connect);

$conn = $connect;

$db = $connect;

}

?

//*/

.

— 数据表结构:

— 100000_insert,1000000_insert

CREATE TABLE `100000_insert` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`parentid` int(11) NOT NULL,

`name` varchar(255) DEFAULT NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8

100000 (10万)行插入:Insert 100000_line_data use 2.5534288883209 seconds

1000000(100万)行插入:Insert 1000000_line_data use 19.677318811417 seconds

//可能报错:MySQL server has gone away

//解决:修改my.ini/my.cnf max_allowed_packet=20M

php如何读取文本指定的内容?

php读取文件内容:

—–第一种方法—–fread()——–

?php

$file_path = “test.txt”;

if(file_exists($file_path)){

$fp = fopen($file_path,”r”);

$str = fread($fp,filesize($file_path));//指定读取大小,这里把整个文件内容读取出来

echo $str = str_replace(“\r\n”,”br /”,$str);

}

?

——–第二种方法————

?php

$file_path = “test.txt”;

if(file_exists($file_path)){

$str = file_get_contents($file_path);//将整个文件内容读入到一个字符串中

$str = str_replace(“\r\n”,”br /”,$str);

echo $str;

}

?

—–第三种方法————

?php

$file_path = “test.txt”;

if(file_exists($file_path)){

$fp = fopen($file_path,”r”);

$str = “”;

$buffer = 1024;//每次读取 1024 字节

while(!feof($fp)){//循环读取,直至读取完整个文件

$str .= fread($fp,$buffer);

}

$str = str_replace(“\r\n”,”br /”,$str);

echo $str;

}

?

——-第四种方法————–

?php

$file_path = “test.txt”;

if(file_exists($file_path)){

$file_arr = file($file_path);

for($i=0;$icount($file_arr);$i++){//逐行读取文件内容

echo $file_arr[$i].”br /”;

}

/*

foreach($file_arr as $value){

echo $value.”br /”;

}*/

}

?

—-第五种方法——————–

?php

$file_path = “test.txt”;

if(file_exists($file_path)){

$fp = fopen($file_path,”r”);

$str =””;

while(!feof($fp)){

$str .= fgets($fp);//逐行读取。如果fgets不写length参数,默认是读取1k。

}

$str = str_replace(“\r\n”,”br /”,$str);

echo $str;

}

?

PHP读取目录下所有文件

php中读取目录下的文件名的方式确实不少,最简单的是scandir,具体代码如下:

$dir=”./目录名/”;

$file=scandir($dir);

print_r($file);

PHP读取zip文件的方法示例

本文实例讲述了PHP读取zip文件的方法。分享给大家供大家参考,具体如下:

?php

$zip

=

zip_open(“111.zip”);

if

($zip)

{

while

($zip_entry

=

zip_read($zip))

{

echo

“Name:

.

zip_entry_name($zip_entry)

.

“n”;

echo

“Actual

Filesize:

.

zip_entry_filesize($zip_entry)

.

“n”;

echo

“Compressed

Size:

.

zip_entry_compressedsize($zip_entry)

.

“n”;

echo

“Compression

Method:

.

zip_entry_compressionmethod($zip_entry)

.

“n”;

if

(zip_entry_open($zip,

$zip_entry,

“r”))

{

echo

“File

Contents:n”;

$buf

=

zip_entry_read($zip_entry,

zip_entry_filesize($zip_entry));

echo

“$buf\n”;

zip_entry_close($zip_entry);

}

echo

“n”;

}

zip_close($zip);

}

?

运行效果截图如下:

更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP操作zip文件及压缩技巧总结》、《php文件操作总结》、《php正则表达式用法总结》、《PHP运算与运算符用法总结》、《PHP基本语法入门教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家PHP程序设计有所帮助。

如何使用PHP读取文本文件内容

利用PHP读取文本文件的内容,其实很简单,我们只需要掌握函数“file_get_contents();”的使用就可以了。下面,小编将作详细的介绍。

工具/原料

电脑一台

WAMP开发环境

方法/步骤

file_get_content()函数介绍。使用file_get_contents()获取txt文件的内容,具体参数说明如下:

2

具体实例说明。从文本文件tst.txt中读取里面的内容并显示在浏览器中,具体代码和图示如下:

?php

$file = ‘tst.txt’;

$content = file_get_contents($file); //读取文件中的内容

echo $content;

?

原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/311363.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
小蓝小蓝
上一篇 2025-01-05 13:23
下一篇 2025-01-05 13:23

相关推荐

  • Python中引入上一级目录中函数

    Python中经常需要调用其他文件夹中的模块或函数,其中一个常见的操作是引入上一级目录中的函数。在此,我们将从多个角度详细解释如何在Python中引入上一级目录的函数。 一、加入环…

    编程 2025-04-29
  • Python周杰伦代码用法介绍

    本文将从多个方面对Python周杰伦代码进行详细的阐述。 一、代码介绍 from urllib.request import urlopen from bs4 import Bea…

    编程 2025-04-29
  • Python中capitalize函数的使用

    在Python的字符串操作中,capitalize函数常常被用到,这个函数可以使字符串中的第一个单词首字母大写,其余字母小写。在本文中,我们将从以下几个方面对capitalize函…

    编程 2025-04-29
  • Python字符串宽度不限制怎么打代码

    本文将为大家详细介绍Python字符串宽度不限制时如何打代码的几个方面。 一、保持代码风格的统一 在Python字符串宽度不限制的情况下,我们可以写出很长很长的一行代码。但是,为了…

    编程 2025-04-29
  • vue下载无后缀名的文件被加上后缀.txt,有后缀名的文件下载正常问题的解决

    本文旨在解决vue下载无后缀名的文件被加上后缀.txt,有后缀名的文件下载正常的问题,提供完整的代码示例供参考。 一、分析问题 首先,需了解vue中下载文件的情况。一般情况下,我们…

    编程 2025-04-29
  • Python基础代码用法介绍

    本文将从多个方面对Python基础代码进行解析和详细阐述,力求让读者深刻理解Python基础代码。通过本文的学习,相信大家对Python的学习和应用会更加轻松和高效。 一、变量和数…

    编程 2025-04-29
  • 如何在Java中拼接OBJ格式的文件并生成完整的图像

    OBJ格式是一种用于表示3D对象的标准格式,通常由一组顶点、面和纹理映射坐标组成。在本文中,我们将讨论如何将多个OBJ文件拼接在一起,生成一个完整的3D模型。 一、读取OBJ文件 …

    编程 2025-04-29
  • Python中set函数的作用

    Python中set函数是一个有用的数据类型,可以被用于许多编程场景中。在这篇文章中,我们将学习Python中set函数的多个方面,从而深入了解这个函数在Python中的用途。 一…

    编程 2025-04-29
  • Python程序文件的拓展

    Python是一门功能丰富、易于学习、可读性高的编程语言。Python程序文件通常以.py为文件拓展名,被广泛应用于各种领域,包括Web开发、机器学习、科学计算等。为了更好地发挥P…

    编程 2025-04-29
  • 三角函数用英语怎么说

    三角函数,即三角比函数,是指在一个锐角三角形中某一角的对边、邻边之比。在数学中,三角函数包括正弦、余弦、正切等,它们在数学、物理、工程和计算机等领域都得到了广泛的应用。 一、正弦函…

    编程 2025-04-29

发表回复

登录后才能评论