如何使用PHP从.dat文件中检索单独的数据行


How to retrieve individual lines of data from a .dat file using PHP?

我不知道如何使用PHP从.dat文件中检索单独的数据行(例如,名字、年龄、出生年份、性别)。我被网上读到的所有东西弄糊涂了。我需要从.dat文件中提取每一行的文本,并为每一行分配自己的$variable,以便稍后用于打印。到目前为止我所拥有的。

<?php
$personalinfo = fopen("personaldata.dat", "r");
$firstname = <!-- line one of .dat file -->;
$age = <!-- line two of .dat file -->;
$birthyear = <!-- line three of .dat file -->;
$sex = <!-- line four of .dat file -->;
$weight = <!-- line five of .dat file -->;
fclose($personalinfo);
print("<p> $firstname you are $age years old, born in $birthyear, you are $weight lbs. and $sex.</p>")
?>    

Dat文件格式

.dat文件有多种格式。首先,您必须确定数据在.dat文件中的格式。听起来你是在说文件是行分隔的(每一行都代表一个值。)

访问文件行(文件功能)

PHP使得一次获取一行文件资源变得很容易,因为file函数返回由文件行组成的数组:

<?php
$personalinfo = file("personaldata.dat");
$firstname = $personalinfo[0];
$age = $personalinfo[1];
$birthyear = $personalinfo[2];
$sex = $personalinfo[3];
$weight = $personalinfo[4];
print("<p> $firstname you are $age years old, born in $birthyear, you are $weight lbs. and $sex.</p>");

访问文件行(老派)

<?php
$personalinfo = fopen("personaldata.dat", "r");
$firstname = fgets($personalinfo);
$age = fgets($personalinfo);
$birthyear = fgets($personalinfo);
$sex = fgets($personalinfo);
$weight = fgets($personalinfo);
fclose($personalinfo);
print("<p> $firstname you are $age years old, born in $birthyear, you are $weight lbs. and $sex.</p>");