Writing a String to a File without a File Handle in PHP

Q

How To Write a String to a File without a File Handle in PHP?

✍: FYIcenter.com

A

If you have a string, want to write it to a file, and you don't want to open the file with a file handle, you can use the file_put_contents(). It opens the specified file, writes the specified string, closes the file, and returns the number of bytes written. Here is a PHP script example on how to use file_put_contents():

<?php
$string = "Download PHP scripts at dev.fyicenter.com.\r\n";
$string .= "Download Perl scripts at dev.fyicenter.com.\r\n";
$bytes = file_put_contents("/temp/todo.txt", $string);
print("Number of bytes written: $bytes\n");
?>

This script will print:

Number of bytes written: 89

If you look at the file todo.txt, it will contain:

Download PHP scripts at dev.fyicenter.com.
Download Perl scripts at dev.fyicenter.com.

 

Writing an Array to a File without File Handle in PHP

Writing a String to a File with a File Handle in PHP

Reading and Writing Files in PHP

⇑⇑ PHP Tutorials

2016-11-27, 1824🔥, 0💬