Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/236.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用PHP函数创建新的txt文件_Php_File_Function - Fatal编程技术网

使用PHP函数创建新的txt文件

使用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

我正在尝试编写一个函数,该函数使用两个参数(文件名和要放入其中的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 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!');