使用PHP函数创建新的txt文件
我正在尝试编写一个函数,该函数使用两个参数(文件名和要放入其中的sting)创建一个包含字符串的新文件使用PHP函数创建新的txt文件,php,file,function,Php,File,Function,我正在尝试编写一个函数,该函数使用两个参数(文件名和要放入其中的sting)创建一个包含字符串的新文件 <?php function writeFile($name, $string) { $text = $string; $fh = fopen($name + ".txt", 'w') or die("Could not create the file."); fwrite($fh, $text) or die("Could not write to the f
<?php
function writeFile($name, $string) {
$text = $string;
$fh = fopen($name + ".txt", 'w') or die("Could not create the file.");
fwrite($fh, $text) or die("Could not write to the file.");
fclose($fh);
echo "File " . $name . ".txt created!";
}
writeFile("testovFail", "Lorem ipsum dolor sit amet");
if(file_exists("testovFail.txt")) echo "<br>File exists!";
?>
这就是我到目前为止所做的,函数会回显文件已创建,但当我运行IF条件检查文件是否已创建时,它会返回文件未创建
function writeFile($name, $string) {
$filename = $name.".txt";
$text = "helloworld";
$fp = fopen($filename,"a+");
fputs($fp,$string);
fclose($fp);
}
这应该能做到——希望到目前为止能做到。
使用+w可以删除文件中已有的内容,使用+可以将其附加到文本中。尝试以下操作:fopen($name..txt,'w')
$name+“.txt”始终返回0
$name+“.txt”
这不是php的工作方式。它应该是$name.txt'
您的代码将按原样创建名为0
的文件,因为它将$name
(在给定的示例中是string
)的值添加到string
和(int)'somestring'==0
如何改为使用
这里有一个稍微不同的方法。:)
查看一下文件\u put\u contents()
-它与fopen()
、fwrite()
和fclose()
的功能相同。您还应该检查fwrite()
(如果您使用file\u put\u contents()
)的返回。
$current = "John Smith";
file_put_contents("blabla.txt", $current);
<?php
$file = new SplFileObject('file.txt', 'w');
$file->fwrite('Hi!');