Alternative to file_get_contents?
file_get_contents() is a built-in PHP function that is commonly used to read the contents of a file into a string. An alternative to this function is using the fopen() and fread() functions.
Example:
<?php
// Open the file for reading
$file = fopen("file.txt", "w");
// Check if the file was successfully opened
if ($file) {
// Write fake content to the file
fwrite($file, "This is some content.");
// Close the file
fclose($file);
// Open the file for reading again
$file = fopen("file.txt", "r");
// Get the size of the file in bytes
$file_size = filesize("file.txt");
// Read the contents of the file
$contents = fread($file, $file_size);
// Output the contents of the file
echo $contents;
// Close the file
fclose($file);
} else {
// If the file could not be opened, output an error message
echo "Error: Could not open the file for writing.";
}
?>
Watch a video course
Learn object oriented PHP
Another alternative is using the file() function, which reads the entire file into an array, with each element representing a line of the file.
Example:
<?php
// Open file "file.txt" in write mode
$file = fopen("file.txt", "w");
// Write three lines of text to the file
fwrite($file, "Line 1\nLine 2\nLine 3");
// Close the file
fclose($file);
// Read the contents of the file into an array, where each line is an element in the array
$lines = file("file.txt");
// Loop through the array and output each line
foreach ($lines as $line) {
// Output the line with a line break
echo $line . "\r\n";
}
And also a modern way is using the file_get_contents() with stream_context_create()
<?php
// Define custom HTTP headers
$options = [
'http' => [
'method' => "GET",
'header' => "Accept-language: en\r\n" . "Cookie: foo=bar\r\n",
],
];
// Create a stream context with the custom headers
$context = stream_context_create($options);
// Make an HTTP GET request to a URL that returns data and pass in the stream context
$file = file_get_contents('http://jsonplaceholder.typicode.com/posts', false, $context);
// Output the response
echo $file;
?>
It's up to you to choose which one suits your needs best.