ExpertRefresh

Streams / File contents  

Related Pages

File open
Read file
Read csv
File contents
File cache and stats
File lock
File parse
Context
Network


0.0% 100%
 
 
0 pages 298 questions
1) Read a file as string







readfile() - Outputs a file <?php // This is useful when you need to include static files, // as it offer smuch better performance and resource utilization than C-style functions header("Content-type: application/pdf"); readfile("zce-php.pdf"); file() - read a file into an array of lines <?php /* --- example.txt -- aaa bbb ccc */ $arr = file("example.txt"); print_r($arr); // Array ( [0] => aaa [1] => bbb [2] => ccc ) file_get_contents() - load an entire file into memory (returns the file as string) <?php // Prior to PHP 4.3.0, it was common to use this function // together with implode() as a quick-and-dirty way to load an entire file into memory. // Old way $file = implode("r", file("example.txt")); // New way $file = file_get_contents("example.txt"); <?php $file = file_get_contents(""); echo $file; // use urlencode for URI with special characters like space (?a=Hello World) <?php /* --- example.txt -- aaa bbb ccc */ // Read 3 characters starting from 2st character $file = file_get_contents("example.txt", NULL, NULL, 2, 3); echo $file; // Outputs: a b (anb) // Second param can be: NULL, TRUE or FILE_USE_INCLUDE_PATH (php > 5) // Third param refers to Stream context file_put_contents() - allows you to write the contents of a PHP string to a file in one pass: <?php touch("example.txt"); $data = "My Data"; file_put_contents("example.txt", $data); // example.txt content is now: My Data // using flags $data = "My Data2"; file_put_contents("example.txt", $data, FILE_APPEND); // content now: My DataMy Data2 // LOCK_EX flag to prevent anyone else writing to the file at the same time file_put_contents("example.txt", "xxx", FILE_APPEND | LOCK_EX); // --- Look Here --- // <?php // When using an array, will automatically apply the equivalent of implode('', $array) touch("example.txt"); $data = array("xxx", "yyy", "zzz"); file_put_contents("example.txt", $data); // content_file: xxxyyyzzz


References