Home >Backend Development >PHP Tutorial >PHP file processing technology sharing: familiar with common methods and techniques of reading and writing
Sharing of PHP file processing technology: Familiar with common methods and techniques for reading and writing
In PHP development, file processing is one of the very common tasks. Whether reading file contents or writing new data, proficiency in file processing technology is a must for PHP developers. This article will share with you some commonly used file processing methods and techniques, as well as related code examples.
1. Read file contents
//Example 1: Read text file
$file = 'example.txt';
$content = file_get_contents($file);
echo $content;
// Example 2: Read JSON file
$file = 'example.json';
$json = file_get_contents($file);
$data = json_decode($json, true);
print_r($data);
//Example 3: Read XML file
$file = 'example.xml';
$xmlString = file_get_contents($file);
$xml = simplexml_load_string($xmlString);
print_r($xml);
?>
$file = fopen('example.txt', 'r');
if ($file) {
while (($line = fgets($file)) !== false) { echo $line; } fclose($file);
}
?>
2. Write file contents
// Example 1: Write text file
$file = 'example.txt';
$content = "Hello, world!";
file_put_contents($file, $content);
//Example 2: Write JSON file
$file = 'example.json';
$data = ["name" = > "John", "age" => 25];
$json = json_encode($data);
file_put_contents($file, $json);
// Example 3: Write XML file
$file = 'example.xml';
$xml = "
file_put_contents($file, $xml);
?>
$file = fopen('example.txt', 'w');
if ($file) {
$content = "Hello, world!"; fwrite($file, $content); fclose($file);
}
?>
3. Other common file processing techniques
$file = 'example.txt';
if (file_exists($file)) {
echo "文件存在";
} else {
echo "文件不存在";
}
?>
$source = 'example.txt';
$destination = 'new.txt';
copy($source, $destination);
?>
$file = 'example.txt';
unlink($file);
?>
Summary:
The above introduces the commonly used methods and techniques in PHP file processing, including common methods of reading file content and writing file content, and gives relevant code examples. It is very important for PHP developers to be proficient in these file processing technologies. I hope this article can help everyone handle file operations better.
The above is the detailed content of PHP file processing technology sharing: familiar with common methods and techniques of reading and writing. For more information, please follow other related articles on the PHP Chinese website!