我无法理解如何使用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>")
?>
答案 0 :(得分:2)
数据文件格式
.dat文件有多种格式。首先,您必须确定如何在.dat文件中格式化数据。听起来你说文件是行分隔的(每一行代表一个值。)
访问文件行(文件功能)
PHP可以轻松地一次抓取一行文件资源,因为文件函数返回一个由文件行组成的数组:
<?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>");