在我的目录中,我有一个list.csv
形式:
RP2015, active
Hope, paused
Process99, active
我正在编写一个php脚本,允许网络用户将不同的行从“活动”切换为“暂停”并返回。不幸的是,我遇到了麻烦。我目前的代码是:http://whitewaterwriters.com/Driver/index.php
它看起来像这个
<HTML>
<Body>
<?
if ($_POST != null) {
$target = $_POST ['sprint'];
echo "<br>Target was:".$target;
$replacement=str_replace('active','paused',$target);
if (strpos($target,'paused') !== false) {
$replacement=str_replace('paused','active',$target);
}
echo "<br>Replacement was:".$replacement."<br>";
$filename = "list.csv";
$contents = file_get_contents($filename);
print "<br>contents was:".$contents;
$new_contents = str_replace($target, $replacement, $contents);
print "<br>contents became:".$new_contents;
file_put_contents($filename, $new_contents);
}
?>
<br><br>
<?php
$row = 1;
if (($handle = fopen("list.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
echo '<form action="index.php" method=post>';
echo $data[0] . $data[1];
echo '<button type="submit" value="'. $data[0].", ".$data[1].'" name="sprint">Pause</button></form><br>';
}
fclose($handle);
}
?>
</body>
</html>
由于某种原因,更换不会触发。捕获事件,正确的目标和替换字符串(我认为)生成,但替换不会出来。我得到的输出是:
Target was:RP2015, active
Replacement was:RP2015, paused
contents was:RP2015, active
contents became:RP2015, active
RP2015 active
谁能告诉我发生了什么事?
编辑:
当前list.csv正是:
RP2015, active
`
答案 0 :(得分:0)
试试这个: -
$ fp = fopen($ filename,“wb”);
$ handle = fopen($ filename,“wb”);
$ replacement = str_replace(“active”,“paused”,$ fp);
$ numbytes = fwrite($ handle,$ replacement);
FCLOSE($处理);
答案 1 :(得分:0)
我忘记的是html将连续的空格拼凑在一起,这就是为什么$ target看起来很好。实际上:
$data[0].", ".$data[1]
只需要
$data[0].",".$data[1]
因为csv解析留下了空间。我将来会使代码更加健壮。
对于感兴趣的人 - 我写的这个辅助函数帮助我找到错误:
function toask($inStr){
$arr1 = str_split($inStr);
foreach ( $arr1 as $a){
print ord($a)." ";
}
}
它将字符串转换为ascii代码序列,您可以确定,例如,引号字符是您认为的字符...