读取文件并存储到变量中

时间:2013-06-13 10:21:20

标签: php html

<?php

$userName = array();
$tutorial = array();
$myFile = "students.txt";
$fh = fopen($myFile,'r');
while( !feof($myFile) ){
    $userName[] = array(fgets($fh));//Save first line content
    $tutorial[] = array(fgets($fh));//Save second line content
}
fclose($myFile);
echo "$userName";
echo "$tutorial";
?>

和我的students.txt内容

dasdsa
A
asdasd
D

如何读取并存储到不同的数组并打印出来

4 个答案:

答案 0 :(得分:1)

您的代码应该按预期工作。我假设你对echo "$userName";输出感到困惑,因为它显示了Array字。尝试var_dump($userName)而不是

答案 1 :(得分:0)

在PHP中使用函数file()

  

file - 将整个文件读入数组

$array_lines = file('students.txt');
$count =  count($array_lines);

$first_arr = array();
$sec_arr = array();
foreach ($array_lines as $i => $line){
   if($i%2) $first_arr[] = $line;
   else $sec_arr[] = $line;
}

print_r($first_arr);
print_r($sec_arr);

使用 file()函数,每一行都被读作数组中的元素。您可以查看:

print_r($first_arr);

答案 2 :(得分:0)

完全按照你的意愿行事,但改变

$userName[] = array(fgets($fh));//Save first line content
$tutorial[] = array(fgets($fh));//Save second line content

$userName[] = fgets($fh);//Save first line content
$tutorial[] = fgets($fh);//Save second line content

(不需要将子项保存在他们自己的单独数组中)

并使用print_r将其打印出来,或者通过它们进行迭代:

for ($i = 0; $i < count($userName); $i++) {
    echo $userName[$i] . " - " . $tutorial[$i];
}

答案 3 :(得分:0)

$text = file_get_contents('students.txt');
$text = explode("\n",$text);
$output = array();
foreach($text as $line)
{  
    $output[] = $line;
}