In many web development projects, we often need to save data to files or read data from files. PHP offers a variety of built-in functions to easily accomplish data output and storage tasks.
PHP includes many file operation functions. Here are some commonly used ones:
- fopen() — Open a file or URL
- fclose() — Close an open file pointer
- fgets() — Read one line from a file pointer
- fread() — Read file contents, suitable for binary files
- fwrite() — Write a string to a file (replaces deprecated fputs())
To write data to a text file, you can use the file_put_contents() function:
$data = "Hello World!\n";
file_put_contents('myfile.txt', $data);
The first parameter is the target file path, and the second parameter is the data to write. This function automatically handles opening and closing the file.
CSV files are a common format for tabular data. You can write CSV files using the fputcsv() function:
$data = array(
array('John', 'Doe', '[email protected]'),
array('Jane', 'Doe', '[email protected]')
);
$fp = fopen('myfile.csv', 'w');
foreach ($data as $row) {
fputcsv($fp, $row);
}
fclose($fp);
This code writes a two-dimensional array to a CSV file by opening the file pointer, writing each row, and then closing the file.
JSON is a widely used format for structured data. You can encode data with json_encode() and write it using file_put_contents():
$data = array(
'name' => 'John Doe',
'email' => '[email protected]'
);
$json = json_encode($data);
file_put_contents('myfile.json', $json);
This saves the array as a JSON string in a file, making it easy to read and parse later.
XML is suitable for complex structured data and can be created using PHP’s DOMDocument class:
$data = array(
'name' => 'John Doe',
'email' => '[email protected]'
);
$doc = new DOMDocument();
$root = $doc->createElement('data');
$doc->appendChild($root);
foreach ($data as $key => $value) {
$elem = $doc->createElement($key);
$text = $doc->createTextNode($value);
$elem->appendChild($text);
$root->appendChild($elem);
}
$doc->save('myfile.xml');
This code builds an XML document by creating elements and text nodes, then saves it to a file.
This article introduced common PHP file operation functions and their usage, covering writing to text, CSV, JSON, and XML files. Developers can select the appropriate format and method to efficiently handle data output and storage. Additionally, database and caching solutions can be combined to further enhance data management.