Reading / Writing a File

readfile()

<pre><?php readfile(dirname(__FILE__) . "/index.html")?></pre>

file_get_contents()

<?php
    $contents = file_get_contents(dirname(__FILE__) . "/index.html");
    $contents = trim($contents,"\n");
    echo nl2br($contents);
?>

file() - Read file as Array

file() function in php reads whole file as an array separated by "\n".

<?php
$contents = file(dirname(__FILE__) . "/index.html");

foreach($contents as $content) {

    echo $content.'<br>';

}
?>

C-Like File Functions

<?php

    $file = fopen("sample.txt", "r");
    while (!feof($file)) {
        echo fgets($file), "<BR>";
    }

?>

Reading from a URL

<?php $file = fopen("http://www.php.net/file.txt", "r"); ?>

Writing to a file

<?php
    $file = fopen("agent.log", "a");
    fputs($file, $_SERVER['HTTP_USER_AGENT']."\n");
?>

Writing to a file Simplified (PHP5)

<?php
    file_put_contents("agent.log", $_SERVER['HTTP_USER_AGENT'], FILE_APPEND);
?>

C-Like functions

<?php
    $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);
?>

 


Loading ...

Related Results :

  1. Reading / Writing a File
Note :
  • Related Posts are generally User Blog posts.
  • or Other tutorials from other networks of w3clan.com.
  • Any registered user can create related posts based on search term tags.

About the Author