我正在尝试更新像这样被阻止的文件
0,0,5,2,0
0,0,7,0,0
0,2,2,3,0
1,2,2,2,0
0,0,5,2,0
0,1,3,2,1
0,0,3,2,2
0,0,6,1,0
每行都是一个问题,行中的每个数字都是受访者的数量。这里的代码试图逐行,并检查用户从每个问题的5个单选按钮中选择的答案。所以格式如下:
Question 1: Blah | 1 | 2 | 3 | 4 | 5 | Check one
//Grab user input from survey
$q[1] = $_POST['radio1'];
$q[2] = $_POST['radio2'];
$q[3] = $_POST['radio3'];
$q[4] = $_POST['radio4'];
$q[5] = $_POST['radio5'];
$q[6] = $_POST['radio6'];
$q[7] = $_POST['radio7'];
$q[8] = $_POST['radio8'];
//Use file handle and write to file
$FileName = "results.csv";
$FileHandle = fopen($FileName, 'a+') or die("can't open file!!");
$i = 0;
while($row = fgetcsv($FileHandle)){
$j = 1;
for($i = 0; $i<8; $i++){
if($q[$j] == 1){
$row[0]++;
}
else if($q[$j] == 2){
$row[1]++;
}
else if($q[$j] == 3){
$row[2]++;
}
else if($q[$j] == 4){
$row[3]++;
}
else if($q[$j] == 5){
$row[4]++;
}
$j++;
}
}
答案 0 :(得分:1)
\n
之类的转义序列不会在单引号内插入。
你必须使用双引号:
$result = $q1.','.$q2.','.$q3.','.$q4.','.$q5.','.$q6.','.$q7.','.$q8."\n";
此外,您应该查看fputcsv()
函数。
答案 1 :(得分:1)
检查fputcsv():http://php.net/manual/en/function.fputcsv.php而不是fwrite,这将为您提供比字符串连接更多的灵活性。
e.g
$q[1] = $_POST['radio1'];
$q[2] = $_POST['radio2'];
$q[3] = $_POST['radio3'];
$q[4] = $_POST['radio4'];
$q[5] = $_POST['radio5'];
$q[6] = $_POST['radio6'];
$q[7] = $_POST['radio7'];
$q[8] = $_POST['radio8'];
fputcsv($FileHandlem $q);
答案 2 :(得分:0)
这是我对我的问题的解决方案,它可能不是优雅但它的工作原理。脚本必须提取值并在最后更新它们。
<?php
//Grab user input from survey
$q[1] = $_POST['radio1'];
$q[2] = $_POST['radio2'];
$q[3] = $_POST['radio3'];
$q[4] = $_POST['radio4'];
$q[5] = $_POST['radio5'];
$q[6] = $_POST['radio6'];
$q[7] = $_POST['radio7'];
$q[8] = $_POST['radio8'];
//Use file handle and write to file
$FileName = "results.csv";
$FileHandle = fopen($FileName, 'r') or die("can't open file!!");
$result = array();
$i = 0;
$j = 1;
while(($row = fgetcsv($FileHandle, 1024, ",")) !== FALSE){
if($q[$j] == 1){
$temp[0] = $row[0] + 1;
$temp[1] = $row[1];
$temp[2] = $row[2];
$temp[3] = $row[3];
$temp[4] = $row[4];
}
else if($q[$j] == 2){
$temp[0] = $row[0];
$temp[1] = $row[1] + 1;
$temp[2] = $row[2];
$temp[3] = $row[3];
$temp[4] = $row[4];
}
else if($q[$j] == 3){
$temp[0] = $row[0];
$temp[1] = $row[1];
$temp[2] = $row[2] + 1;
$temp[3] = $row[3];
$temp[4] = $row[4];
}
else if($q[$j] == 4){
$temp[0] = $row[0];
$temp[1] = $row[1];
$temp[2] = $row[2];
$temp[3] = $row[3] + 1;
$temp[4] = $row[4];
}
else if($q[$j] == 5){
$temp[0] = $row[0];
$temp[1] = $row[1];
$temp[2] = $row[2];
$temp[3] = $row[3];
$temp[4] = $row[4] + 1;
}
$result[] = $temp;
$j++;
}
fclose($FileHandle);
$FileHandle = fopen($FileName, 'w') or die("can't open file!!");
foreach($result as $line){
fputcsv($FileHandle, $line);
}
fclose($FileHandle);
?>