我需要在PHP中设置一个动态文件名。所以我写了一个小的示例脚本来表示我面临的问题。
当我运行以下脚本时,我得到以下错误的输出,并且创建的文件只是命名为.csv
,而它应该被命名为0101.csv
输出:
Notice: Undefined variable: 65 in C:'xampp'htdocs'testsEight.php on line 5
Notice: Undefined variable: 65 in C:'xampp'htdocs'testsEight.php on line 7
Array ( [0] => BillClinton )
为什么它将变量称为65
而不是$the_id
?我正在尝试遵循这些准则。在下面的代码中,我也尝试用${$the_id}
替换它,没有运气!
法典:
<?php
$type = 'BillClinton';
$the_id = 0101;
file_put_contents ( 'C:/'.$$the_id.'.csv' , $type ."," , FILE_APPEND );
$file = fopen('C:/'.$$the_id.'.csv', 'r');
$line = fgetcsv($file);
array_pop($line);
if ($line !== FALSE) {
//$line is an array of the csv elements in a line. The fgetcsv() function parses a line from an open file, checking for CSV fields.The fgetcsv() function stops returning on a new line, at the specified length, or at EOF, whichever comes first.
print_r($line);//check
} else {echo 'FALSE';}
请帮我解决这个问题。
您在$$the_id
中使用了两个$
,在$the_id = 0101;
中使用了一个
"为什么它将变量称为 65">
前导零将0101
视为八进制,因此请用引号括起来$the_id = "0101";
你在 $$the_id 中有额外的 $,这导致调用变量名 the_id 的 $the_id intead 的引用。所以你需要抹去它。代码将如下所示;
<?php
$type = 'BillClinton';
$the_id = 0101;
file_put_contents ( 'C:/'.$the_id.'.csv' , $type ."," , FILE_APPEND );
$file = fopen('C:/'.$the_id.'.csv', 'r');
$line = fgetcsv($file);
array_pop($line);
if ($line !== FALSE) {
//$line is an array of the csv elements in a line. The fgetcsv() function parses a line from an open file, checking for CSV fields.The fgetcsv() function stops returning on a new line, at the specified length, or at EOF, whichever comes first.
print_r($line);//check
} else {echo 'FALSE';}
有关更多详细信息,您可以查看 PHP 文档
首先,你的例子是错误的。PHP 永远不会允许您定义整数,甚至不允许将"字符串转换"整数定义为变量名。
脚本中唯一的问题是您使用双美元符号,这是对$0101
的引用(假设$the_id
0101
字符串或整数,没关系(。
简单的解决方案是删除您的双美元登录:
file_put_contents ( 'C:/'.$the_id.'.csv' , $type ."," , FILE_APPEND );
$file = fopen('C:/'.$the_id.'.csv', 'r');
这背后的想法是变量的名称可以是变量。这就是你的问题上升的方式。
$a = 'hello';
$$a = 'world';
echo $hello; // will output 'world';
问候。