PHP - 使用fwrite添加预定义文本和会话变量

时间:2013-05-14 06:13:53

标签: php session variables printf

在下面的代码中,我希望能够在PHP脚本写入变量$ name,$ age和$ email之前包含“Name:”,“Age:”和“Email:”。

看起来很简单,但我无法让它发挥作用!

<?php

session_start();

$name = $_SESSION['name']; 
$age = $_SESSION['age'];
$email =  $_SESSION['email'];

$handle = fopen('users.txt', 'a');
fwrite($handle, $name."\n"); 

$handle = fopen('users.txt', 'a');
fwrite($handle, $age."\n"); 

$handle = fopen('users.txt', 'a');
fwrite($handle, $email."\n"); 

fclose($handle); 

?>

我试过这个:

<?php

session_start();

$name = $_SESSION['name']; 
$age = $_SESSION['age'];
$email =  $_SESSION['email'];

$handle = fopen('users.txt', 'a');
fwrite($handle, 'Name:', $name."\n"); 

$handle = fopen('users.txt', 'a');
fwrite($handle, 'Age:', $age."\n"); 

$handle = fopen('users.txt', 'a');
fwrite($handle, 'Email', $email."\n"); 

fclose($handle); 

?>

但是,在user.txt文档中打印的所有内容都是“年龄:”。

任何帮助将不胜感激,谢谢!

更新:删除了多个fopen并将','替换为'。'一切都很完美,感谢每个人的帮助!

2 个答案:

答案 0 :(得分:2)

<?php

session_start();

$data = array(
    'Name:'  . (isset($_SESSION['name'])  ? $_SESSION['name']  : '') ,
    'Age:'   . (isset($_SESSION['age'])   ? $_SESSION['age']   : '') ,
    'Email:' . (isset($_SESSION['email']) ? $_SESSION['email'] ; '') ,
);

if ($fp = fopen('users.txt','a')) {
    fwrite($fp,implode(PHP_EOL,$data).PHP_EOL); 
    fclose($fp);
} else {
    die('Error');
}

答案 1 :(得分:0)

使用可以使用此

$fp = fopen('users.txt', 'a');

fwrite($fp, 'Name : '.$name . PHP_EOL);
fwrite($fp, 'Age : '.$age . PHP_EOL);
fwrite($fp, 'Email : '.$email . PHP_EOL);

fclose($fp);