对于学校作业,我必须用 PHP 编写脚本。它必须创建一个带有名称的数组并将该数组写入文件。然后它必须删除数组,读取文件中的名称并回显它们。
这不起作用:
<?php
$names = array("Name 1", "Name 2", "Name 3", "Name 4", "Name 5");
$filename = "names.txt";
$handle = fopen($filename, "wb+"); //open as read and write
$string = implode("\r\n", $names); //name on each line
fwrite($handle, $string); //write line
$names = array(); //empty array
print_r($names); //print empty array
$string = fread($handle, filesize($filename)); //read file
$names = explode("\r\n", $string); //lines to array
foreach ($names as $name) {
echo("<br>\n$name");
}
fclose($handle);
?>
但这有效:
<?php
$names = array("Name 1", "Name 2", "Name 3", "Name 4", "Name 5");
$filename = "names.txt";
$handle = fopen($filename, "wb"); //open as write
$string = implode("\r\n", $names); //name on each line
fwrite($handle, $string); //write line
fclose($handle); //close
$handle = fopen($filename, "r"); //open as read
$names = array(); //empty array
print_r($names); //print empty array
$string = fread($handle, filesize($filename)); //read file
$names = explode("\r\n", $string); //lines to array
foreach ($names as $name) {
echo("<br>\n$name");
}
fclose($handle);
?>
当我关闭并重新打开文件时,我不明白为什么它会起作用。任何帮助,将不胜感激。