从文件中读取

时间:2011-07-04 22:46:23

标签: php

我有内容文件:

Tom TOM is a good student with excellent marks. This profile can be viewed online ar www.x.xom/tom/marks. He is one of the oustanding student
Tom1 TOM is a good student with excellent marks. This profile can be viewed online ar www.x.xom/tom/marks. He is one of the oustanding student
Tom2 TOM is a good student with excellent marks. This profile can be viewed online ar www.x.xom/tom/marks. He is one of the oustanding student

我有很多这样的台词。 每行都有一个名称,后跟一个字符串,直到该行的末尾。

我想要一个PHP脚本,它将读取第一个单词保存在临时变量中。 同样地,我希望直到行尾的所有文本都转到第二个变量。

我用过这些

$myFile = "profiles.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, 5);
fclose($fh);
echo $theData;

但问题是我能够读取前5个字符。我想第一次只读一个字。第二个是要转换为变量的所有字符串。

1 个答案:

答案 0 :(得分:0)

这样的东西?

$myFile = "profiles.txt";
$fh = fopen($myFile, 'r');
$anArray = array();
while (($line = fgets($fg)) !== false) {
  list($name, $restOfLine) = explode(' ', $line, 2);
  // Do something with $name and $restOfLine (e.g. put them in array)
  $anArray[] = array('name' => $name, 'line' => $restofLine);
}
fclose($fh);
var_dump($anArray);