我只是想知道如何使用变量名来在PHP中设置文件名?当我运行以下代码时:
<?php
if ($_POST) {
$filename = $_POST['firstName'];
header("Content-Type: application/txt");
header('Content-Disposition: attachment; filename="$filename.txt"');
echo "Welcome, ";
echo $_POST['firstName']. " " . $_POST['lastName'];
exit;
} else {
?>
<form action="" method="post">
First Name: <input type="text" name="firstName" /><br />
Last Name: <input type="text" name="lastName" /><br />
<input type="submit" name="submit" value="Submit me!" />
</form>
<?php } ?>
文件名始终设置为“$filename.txt
”,但我希望它为Adam.txt
或Brian.txt
等,具体取决于用户输入。
答案 0 :(得分:6)
将''替换为'“,以便变量替换起作用
header("Content-Disposition: attachment; filename=\"$filename.txt\"");
或者如果你想使用''
header('Content-Disposition: attachment; filename="'.$filename.'.txt"');
答案 1 :(得分:0)
只有双引号允许您插入变量:
$a = "some text"
$b = "another part of $a" //works, results in *another part of some text*
$b = 'another part of $a' //will not work, result *in another part of $a*
有关详细信息,请参阅http://php.net/manual/en/language.types.string.php#language.types.string.parsing
答案 2 :(得分:0)
这是因为您使用单引号作为字符串,单引号中的字符串无法解析 - 请参阅the documentation。
要解决此问题,您可以执行此操作:
header('Content-Disposition: attachment; filename="'.$filename.'.txt"');
答案 3 :(得分:0)
<?php
if ($_POST) {
$filename = isset($_POST['firstName'])? $_POST['firstName'] :'general';
header("Content-Type: application/txt");
header('Content-Disposition: attachment; filename='.$filename.'.txt');
echo "Welcome, ";
echo
$_POST['firstName']. " " . $_POST['lastName']; exit;
} else
{
?>
<form action="" method="post">
First Name: <input type="text"
name="firstName" /><br />
Last Name: <input type="text"
name="lastName" /><br /> <input type="submit" name="submit"
value="Submit me!" /> </form>
<?php } ?>
答案 4 :(得分:0)
使用此:
header('Content-Disposition: attachment; filename="'.$filename.'.txt"');