PHP:无法将所有值添加到字符串

时间:2013-02-22 06:07:58

标签: php

我正在尝试将未知数量的参数添加到PHP中的字符串中。

这是代码:

<?php 
print "Get parameters";
$myFile = "wr.txt";
$fh = fopen ($myFile, 'w') or die ("can't open file");
$stringData = '';
//$st = '';
foreach ($_REQUEST as $k => $v) {
        $date = date ('Y-m-d H:i:s');
        $stringData = $k.":".$v."Date:".$date."\n";      
        fwrite ($fh, $stringData);
        fwrite ($fh, $stringData);
        fclose ($fh);
}
?>

但它只添加了最后一个参数值。

我也尝试了

$stringData += $k.":".$v."Date:".$date."\n"; 

并说出来:

fwrite($fh, $stringData);
fwrite($fh, $stringData);
fclose($fh);

在for循环之外,但在这种情况下,它在wr.txt中写入00。请帮助我如何按行编写所有参数。

由于

5 个答案:

答案 0 :(得分:2)

PHP .用于连接+不用于连接。

更改此

$stringData +=$k.":".$v."Date:".$date."\n"; 

$stringData .= $k.":".$v."Date:".$date."\n"; 

答案 1 :(得分:0)

close ($fh)移离循环:

$myFile = "wr.txt";
$fh = fopen ($myFile, 'w') or die ("Can't open file");

$date = date ('Y-m-d H:i:s');
foreach ($_REQUEST as $k => $v)
    fwrite ($fh, "$k: $v Date $date\n") or die ("Cannot write to file");

fclose ($fh);

答案 2 :(得分:0)

使用“。”而不是“+”,在php连接运算符是“。”

答案 3 :(得分:0)

看到线路:

$stringData .=$k.":".$v."Date:".$date."\n";//** ADD CONCATENATION '.' BEFORE '='** 
fwrite($fh, $stringData); //PUT THIS OUT SIDE THE LOOP
fwrite($fh, $stringData); //**REMOVE THIS **
fclose($fh); // **PUT HIS OUT SIDE THE FOREACH LOOP** 

试试这个:

<?php 

print "Get parameters";
$myFile = "wr.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = '';
//$st = '';
foreach($_REQUEST as $k => $v) {
        $date = date('Y-m-d H:i:s');
        $stringData .=$k.":".$v."Date:".$date."\n";//** ADD CONCATENATION '.' BEFORE '='**  
        //fwrite($fh, $stringData); PUT THIS OUT SIDE THE LOOP
        ///fwrite($fh, $stringData); //**REMOVE THIS **
        //fclose($fh); // **PUT HIS OUT SIDE THE FOREACH LOOP**
}
fwrite($fh, $stringData);
fclose($fh);
?>

答案 4 :(得分:0)

我只能猜到你想要做什么。但试试这个:

<?php 
print "Get parameters";
$myFile = "wr.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = '';
//$st = '';
foreach($_REQUEST as $k => $v) {
    $date = date('Y-m-d H:i:s');
    $stringData = $stringData . $k.":".$v."Date:".$date."\n";
}
fwrite($fh, $stringData);
fclose($fh);
?>

希望有所帮助。