PHP中的file_put_contents()函数是一个内置函数,用于将字符串写入文件。file_put_contents()函数检查用户想要写入的文件,如果该文件不存在,它会创建一个新文件。
null
用户要写入的文件路径和必须写入的数据作为参数发送给函数,函数在成功时返回写入文件的字节数,在失败时返回FALSE。
语法:
file_put_contents($file, $data, $mode, $context)
参数: PHP中的file_put_contents()函数接受两个必需参数和两个可选参数。
- $file :指定要写入的文件。
- $data :它指定必须写入文件的数据。它可以是字符串、数组或数据流。
- $context :它是一个可选参数,用于指定自定义上下文或流的行为。
- $mode :这是一个可选参数,用于指定如何将数据写入文件,例如文件\使用\包含\路径、文件\附加、锁定\ EX。
返回值: 成功时返回写入文件的字节数,失败时返回FALSE。
错误和例外 :
- file_put_contents()函数返回Boolean FALSE,但也可能返回一个计算结果为FALSE的非布尔值。
- 如果提供的目录无效,此函数将无法写入内容。
例如:
Input : file_put_contents("gfg.txt", "A computer science portal for geeks!"); Output : 36 Input : $file_pointer = 'gfg.txt'; $open = file_get_contents($file_pointer); $open .= "A computer science portal for geeks!"; file_put_contents($file_pointer, $open); Output : 36
下面的程序演示了file_put_contents()函数。
方案1 :
<?php // writing content on gfg.txt echo file_put_contents ( "gfg.txt" , "A computer science portal for geeks!"); ?> |
输出:
36
方案2 :
<?php $file_pointer = 'gfg.txt' ; // Open the file to get existing content $open = file_get_contents ( $file_pointer ); // Append a new person to the file $open .= "A computer science portal for geeks!" ; // Write the contents back to the file file_put_contents ( $file_pointer , $open ); ?> |
输出:
36
参考: http://php.net/manual/en/function.file-put-contents.php
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END