file_get_contents() is the simplest choice when the entire file can comfortably fit in memory. It returns false on failure, so use a strict comparison before working with the result.
$file = __DIR__ . '/data.txt';
$content = file_get_contents($file);
if ($content !== false) {
echo nl2br(htmlspecialchars($content));
}This example shows the recommended starting pattern. Continue below for variations, explanation and the original practical examples.
$str="my_file.txt"; // Change the path ( end of this page copy the file )
echo file_get_contents($str,1,null,0,120);
Output is here
Welcome to plus2net, Read PHP section here
file_get_contents return the output of a file as a string.
echo file_get_contents(path,include_p,context,offset,length);
path:include_p:context:offset:length:$v1=urlencode('Alex John');
$str="http://127.0.0.1/t/file/file_get_contents-demo.php?name=$v1";
echo $str;
echo "<hr>";
echo file_get_contents($str,1,null,0,20);
Here is the second file where we will read the output file_get_contents-demo.php.
<?Php
$v1=$_GET['name']; // collect from url
$v1=urldecode($v1);
echo "Welcome $v1";
?>
Output: here we are not getting the source code , only the output as returned by the browser is read as string and displayed.
Welcome Alex John
You can change the output by changing the start and max_length optional parameters of the function.
Welcome to plus2net
Read PHP section here
<?php
// Set the specific AMFI scheme code
$schemeCode = "120847";
$apiUrl = "https://api.mfapi.in/mf/" . $schemeCode . "/latest";
// Bypass SSL verification for local environments
$context = stream_context_create([
"ssl" => [
"verify_peer" => false,
"verify_peer_name" => false,
],
]);
// Fetch the JSON response
$jsonResponse = file_get_contents($apiUrl, false, $context);
$data = json_decode($jsonResponse, true);
if (isset($data['data'][0]['nav'])) {
$fundName = $data['meta']['scheme_name'];
$navValue = $data['data'][0]['nav'];
$navDate = $data['data'][0]['date'];
echo "Fund: " . $fundName . " | NAV: " . $navValue . " (as of " . $navDate . ")";
} else {
echo "Error: Scheme data not found.";
}
?>
Reading external url by curl Reading a file by fread()
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.