如何更新 PHP 中的文件
How to update files in PHP
我有一些 PHP 函数需要用作数据库的 CSV 文件的行号。一旦有了行,它就会导航到需要更改的特定值,对其进行更改并重写整个文件。这是我的代码:
<?php
function update($file, $id, $field, $value)
{
//$id is the line number
$contents = explode("\n", file_get_contents($file));
$fh = fopen($file, "w");
$lines = array();
foreach($contents as $line)
{
if($line == "")
continue;
$fields = explode("|", $line);
if($fields[0] == $id)
{
$line = null;
for($i = 0; $i<count($fields); $i++)
{
if($i == $field)
$fields[$i] = $value;
if($i != count($fields)-1)
$line .= $fields[$i]."|";
else
$line .= $fields[$i];
}
}
$line .= "\n";
fwrite($fh, $line);
}
fclose($fh);
$contents = null;
return true;
}
$id = $_SESSION['id'];
$uid = $_GET['p'];
$myfile = "myfile.txt";
if(update($myfile, 12, 14, "somevalue"))
echo "updated!";
?>
我找不到问题,因为每当我 运行 代码时,它都会输出 "updated!" ,但当检查文件时,我发现它没有更新。我不知道为什么,但它总是保持不变!谢谢
检查 fwrite() 是否失败。
做这样的事情:
...
$writeSuccess = (fwrite($fh, $line) !== false);
}
fclose($fh);
$contents = null;
return $writeSuccess;
}
...
如果失败,请检查您的文件系统权限设置是否正确。 Apache 用户需要对您要写入文件的任何内容具有写入权限。file/folder。
我找到问题所在了。
$id = $_SESSION['id'];
$uid = $_GET['p'];
$myfile = "myfile.txt";
if(update($myfile, 12, 14, "somevalue"))
行号指向上一行,导致无法更新文件的第一行。所以我所要做的就是
$line ++;
我有一些 PHP 函数需要用作数据库的 CSV 文件的行号。一旦有了行,它就会导航到需要更改的特定值,对其进行更改并重写整个文件。这是我的代码:
<?php
function update($file, $id, $field, $value)
{
//$id is the line number
$contents = explode("\n", file_get_contents($file));
$fh = fopen($file, "w");
$lines = array();
foreach($contents as $line)
{
if($line == "")
continue;
$fields = explode("|", $line);
if($fields[0] == $id)
{
$line = null;
for($i = 0; $i<count($fields); $i++)
{
if($i == $field)
$fields[$i] = $value;
if($i != count($fields)-1)
$line .= $fields[$i]."|";
else
$line .= $fields[$i];
}
}
$line .= "\n";
fwrite($fh, $line);
}
fclose($fh);
$contents = null;
return true;
}
$id = $_SESSION['id'];
$uid = $_GET['p'];
$myfile = "myfile.txt";
if(update($myfile, 12, 14, "somevalue"))
echo "updated!";
?>
我找不到问题,因为每当我 运行 代码时,它都会输出 "updated!" ,但当检查文件时,我发现它没有更新。我不知道为什么,但它总是保持不变!谢谢
检查 fwrite() 是否失败。
做这样的事情:
...
$writeSuccess = (fwrite($fh, $line) !== false);
}
fclose($fh);
$contents = null;
return $writeSuccess;
}
...
如果失败,请检查您的文件系统权限设置是否正确。 Apache 用户需要对您要写入文件的任何内容具有写入权限。file/folder。
我找到问题所在了。
$id = $_SESSION['id'];
$uid = $_GET['p'];
$myfile = "myfile.txt";
if(update($myfile, 12, 14, "somevalue"))
行号指向上一行,导致无法更新文件的第一行。所以我所要做的就是
$line ++;