Php create php file and write to it

PHP File Create/Write

In this chapter we will teach you how to create and write to a file on the server.

PHP Create File — fopen()

The fopen() function is also used to create a file. Maybe a little confusing, but in PHP, a file is created using the same function used to open files.

If you use fopen() on a file that does not exist, it will create it, given that the file is opened for writing (w) or appending (a).

The example below creates a new file called «testfile.txt». The file will be created in the same directory where the PHP code resides:

Example

PHP File Permissions

If you are having errors when trying to get this code to run, check that you have granted your PHP file access to write information to the hard drive.

PHP Write to File — fwrite()

The fwrite() function is used to write to a file.

The first parameter of fwrite() contains the name of the file to write to and the second parameter is the string to be written.

Читайте также:  What is base64 encoding in java

The example below writes a couple of names into a new file called «newfile.txt»:

Example

$myfile = fopen(«newfile.txt», «w») or die(«Unable to open file!»);
$txt = «John Doe\n»;
fwrite($myfile, $txt);
$txt = «Jane Doe\n»;
fwrite($myfile, $txt);
fclose($myfile);
?>

Notice that we wrote to the file «newfile.txt» twice. Each time we wrote to the file we sent the string $txt that first contained «John Doe» and second contained «Jane Doe». After we finished writing, we closed the file using the fclose() function.

If we open the «newfile.txt» file it would look like this:

PHP Overwriting

Now that «newfile.txt» contains some data we can show what happens when we open an existing file for writing. All the existing data will be ERASED and we start with an empty file.

In the example below we open our existing file «newfile.txt», and write some new data into it:

Example

$myfile = fopen(«newfile.txt», «w») or die(«Unable to open file!»);
$txt = «Mickey Mouse\n»;
fwrite($myfile, $txt);
$txt = «Minnie Mouse\n»;
fwrite($myfile, $txt);
fclose($myfile);
?>

If we now open the «newfile.txt» file, both John and Jane have vanished, and only the data we just wrote is present:

PHP Append Text

You can append data to a file by using the «a» mode. The «a» mode appends text to the end of the file, while the «w» mode overrides (and erases) the old content of the file.

In the example below we open our existing file «newfile.txt», and append some text to it:

Example

$myfile = fopen(«newfile.txt», «a») or die(«Unable to open file!»);
$txt = «Donald Duck\n»;
fwrite($myfile, $txt);
$txt = «Goofy Goof\n»;
fwrite($myfile, $txt);
fclose($myfile);
?>

If we now open the «newfile.txt» file, we will see that Donald Duck and Goofy Goof is appended to the end of the file:

Complete PHP Filesystem Reference

For a complete reference of filesystem functions, go to our complete PHP Filesystem Reference.

Источник

Php create file and write to it php

Also, note the difference between using and from the docs on the topic: Solution 2: function tmpfile — Creates a temporary file Creates a temporary file with a unique name in read-write (w+) mode and returns a file handle . It searches for the file to write in, and if the desired file is not present, it creates a new file.

Create new XML file and write data to it?

DOMDocument is a great choice. It’s a module specifically designed for creating and manipulating XML documents. You can create a document from scratch, or open existing documents (or strings) and navigate and modify their structures.

$xml = new DOMDocument(); $xml_album = $xml->createElement("Album"); $xml_track = $xml->createElement("Track"); $xml_album->appendChild( $xml_track ); $xml->appendChild( $xml_album ); $xml->save("/tmp/test.xml"); 
$xml = new DOMDocument(); $xml->load('/tmp/test.xml'); $nodes = $xml->getElementsByTagName('Album') ; if ($nodes->length > 0) < //insert some stuff using appendChild() >//re-save $xml->save("/tmp/test.xml"); 

PHP has several libraries for XML Manipulation.

The Document Object Model (DOM) approach (which is a W3C standard and should be familiar if you’ve used it in other environments such as a Web Browser or Java, etc). Allows you to create documents as follows

createElement( 'Root' ); $ele->nodeValue = 'Hello XML World'; $doc->appendChild( $ele ); $doc->save('MyXmlFile.xml'); ?> 

Even if you haven’t come across the DOM before, it’s worth investing some time in it as the model is used in many languages/environments.

With FluidXML you can generate and store an XML document very easily.

$doc = fluidxml(); $doc->add('Album', true) ->add('Track', 'Track Title'); $doc->save('album.xml'); 

Loading a document from a file is equally simple.

$doc = fluidify('album.xml'); $doc->query('//Track') ->attr('id', 123); 

How to create and write a file in a specific, w+: will create a new file if it does not exist and overwrite if it exists a: append to file already exist a+: append to file already exist and create a new file if it does not exist If you load path directory from the database, you maybe need to create multi-directory

Writing files to temporary locations

To avoid the Write-Read-Delete cycle with an actual file on disk, I would keep all of your temporary «file» data stored in memory using php’s built-in php://temp and php://memory IO stream wrappers docs .

// open a temporary file handle in memory $tmp_handle = fopen('php://temp', 'r+'); fwrite($tmp_handle, 'my awesome text to be emailed'); // do some more stuff, then when you want the contents of your "file" rewind($tmp_handle); $file_contents = stream_get_contents($tmp_handle); // clean up your temporary storage handle fclose($tmp_handle); 

You never have to write or delete a file to the disk. Also, note the difference between using php://temp and php://memory from the docs on the topic:

php://memory and php://temp are read-write streams that allow temporary data to be stored in a file-like wrapper. The only difference between the two is that php://memory will always store its data in memory, whereas php://temp will use a temporary file once the amount of data stored hits a predefined limit (the default is 2 MB). The location of this temporary file is determined in the same way as the sys_get_temp_dir() function.

function tmpfile — Creates a temporary file

Creates a temporary file with a unique name in read-write (w+) mode and returns a file handle .

The file is automatically removed when closed (using fclose()), or when the script ends.

If you only need it so that you can attach it to an email, you don’t really have to write the file. Just:

$attachment=chunk_split(base64_encode($XML)) $mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x"; // put message body in mime boundries $message = "This is a multi-part message in MIME format.\n\n" . "--\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n"; // attachment with mime $message .= "--\n" . "Content-Type: ;\n" . " name=\"\"\n" . "Content-Transfer-Encoding: base64\n\n" . $attachment. "----\n"; 

untested, but I’ve done something like it before. (I pulled that out of a script I use to send myself backups.)

Create, write and download a txt file using php, create, write and download a txt file using php. Ask Question Asked 3 years, 10 months ago. I create a new file, with only your code and it works. Clcking on a button and triggering this via ajax — doesn’t work. So should I have a special php page just for download?

Write Into a File in PHP

In this article, we will introduce methods to write into a file in PHP.

Use file_put_contents() Function to Write Into a File in PHP

The built-in function file_put_contents() writes the data into a file in PHP. It searches for the file to write in, and if the desired file is not present, it creates a new file. We can use this function to write into a file. The correct syntax to use this function is as follows.

file_put_contents($pathOfFile, $info, $customContext, $mode); 

This function accepts four parameters. The detail of these parameters is as follows.

Parameter Description
$pathOfFile mandatory Path of the file.
$info mandatory Data to write in a file. It can be a string.
$customContext optional Specify a custom context.
$mode optional The mode in which the data will be written on the file.
It can be FILE_USE_INCLUDE_PATH , FILE_APPEND , and LOCK_EX .

This function returns the number of bytes written on the file if successful, or False if it fails.

The following program will write the data into a file.

The number of bytes written is 17. 

Use fopen() , fwrite() and fclose() Functions to Write Into a File in PHP

The built-in functions fopen() , fwrite() and fclose() are used to open a file, write into a file and close a file. The correct syntax to use these functions is as follows

fopen($fileName, $mode, $path, $context); 

This function has four parameters, and their details are as follows.

Parameters Description
$fileName mandatory It is the name of the file to open.
$mode mandatory It is the mode of the file. There are several modes, check here.
$path optional It is the path to search file.
$context optional It is used to set the context of the file.

The possible modes include,

mode Description
r Read only
r+ Read and write
w Write only. If the file does not exist, attempt to create it.
w+ Read and write. If the file does not exist, attempt to create it.
a Append.
a+ Read and append.
x Create and write only.
x+ Create and read and write
fwrite($fileName, $info, $length); 

It has three parameters. The details of its parameters are as follows.

Parameter Description
$fileName mandatory It is the file to write in.
$info mandatory It is the information that will be written in the file.
$length optional It is the number of bytes to be written in the file.

True on success and False on failure.

The below program writes the data into a file.

Here the mode in fopen() function is set to w that means the file is opened for writing only.

The number of bytes written is 17. 

PHP File

PHP Create and Save a txt file to root directory, fopen() will open a resource in the same directory as the file executing the command. In other words, if you’re just running the file ~/test.php, your script will create ~/myText.txt. This can get a little confusing if you’re using any URL rewriting (such as in an MVC framework) as it will likely create the new …

Источник

Оцените статью