不用,用循环 $file = fopen("welcome.txt", "r") or exit("Unable to open file!"); //Output a line of the file until the end is reached $i=0; while(!feof($file)) { if($i>=1) { $str.=fgetss($file).",\"$i"."name"."\""."<br />"; } else { $str.=fgetss($file).",\"content\""."<br />"; } $i++; }
<?php
$sContent = file_get_contents("input.txt");
$iFirst = stripos($sContent, "\n");
$sFirst = substr($sContent, 0, $iFirst-1) . ',"CONTENT"' . "\n";
$iSecode = stripos($sContent, "\n", $iFirst+strlen('\n'));
$sSecode = substr($sContent, $iFirst+strlen('\n')-1, $iSecode-$iFirst-strlen('\n')) . ',"1"'. "\n";
$iThird = stripos($sContent, "\n", $iSecode+strlen('\n'));
$sThird = substr($sContent, $iSecode+strlen('\n')-1, $iThird-$iSecode-strlen('\n')) . ',"2"'. "\n";
$sFour = substr($sContent, $iThird+strlen('\n')-1, -1) .',"3"'. "\n";
echo $sFirst . $sSecode . $sThird . $sFour;
file_put_contents("input.txt", $sFirst . $sSecode . $sThird . $sFour);
?>
可持续往每行后追加,此段可用循环改写
"ID","NAME","AGE"
"1","polo","18"
"2","tony","20"
"3","jack","19"
TEXT;file_put_contents('input.txt', $s);
readfile('input.txt');//以上创建环境并验证if(file_exists('input.bak')) {
unlink('input.bak');
}
rename('input.txt', 'input.bak');$in = fopen('input.bak', 'r');
$out = fopen('input.txt', 'w');$ar = fgetcsv($in);
$ar[] = 'CONTENT';
fputcsv($out, $ar);$ar = fgetcsv($in);
$ar[] = 1;
fputcsv($out, $ar);$ar = fgetcsv($in);
$ar[] = 2;
fputcsv($out, $ar);$ar = fgetcsv($in);
$ar[] = 3;
fputcsv($out, $ar);fclose($in);
fclose($out);readfile('input.txt');//验证结果
ID,NAME,AGE,CONTENT
1,polo,18,1
2,tony,20,2
3,jack,19,3
"ID","NAME","AGE","CONTENT"
"1","polo","18","1"
"2","tony","20","2"
"3","jack","19","3"
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
$i=0;
while(!feof($file))
{
if($i>=1)
{
$str.=fgetss($file).",\"$i"."name"."\""."<br />";
}
else
{
$str.=fgetss($file).",\"content\""."<br />";
}
$i++;
}