Voir aussi:
fgestcsv pour faire du fopen sur du csv
array plus généralement la fonction array, avec un exemple pour ouvrir un fichier csv
if (!$handle = fopen($filename, 'a')) {
echo “erreur…”; exit; }
Using fread () in PHP http://php.about.com/od/advancedphp/ss/php_read_file_2.htm
You can use fread () when you want to read the file data and return it to a string. You can specify how many bytes to read, but 8192 is the maximum. If you choose to use this method, you must be sure to open the file first.
<?php
$YourFile = "YourFile.txt";
$handle = fopen($YourFile, 'r');
$Data = fread($handle, 512);
fclose($handle);
print $Data;
?>
This code opens the file YourFile.txt from your server and puts it's entire contents into the variable $Data as a string. We then print $Data, so the script is basically outputting the file contents onto a page..
Using file_get_contents () in PHP http://php.about.com/od/advancedphp/ss/php_read_file_3.htm
File_get_contents () is similar to fread () in that it returns the entire contents of the file to a single string, however it can be done in a single line and performs better then fread ().
<?php
$file = file_get_contents ('YourFile.txt');
Echo $file;
?>
This little bit of code retrieves the data from YourFile.text and then echos it onto the page.
Using fgets () in PHP http://php.about.com/od/advancedphp/ss/php_read_file_4.htm
Fgets () is used to read the data from a file one line at a time starting from the pointer. It defaults to only reading the first 1024 bytes of a line, however you can set this variable higher or lower if you wish. If your file is not separated with line breaks, this is not the right function to use.
<?php
$YourFile = "YourFile.txt";
$handle = fopen($YourFile, 'r');
while (!feof($handle))
{
$Data = fgets($handle, 256);
print $Data;
print "<p>";
}
fclose($handle);
?>
What this code does first is open the file YourFile.txt. It then enters into a loop that will read up to 256 bytes of the file line, print the contents of the line, print an HTML paragraph break, and then repeat this with the next line until it reaches the end of the file (foef).
Using file () in PHP http://php.about.com/od/advancedphp/ss/php_read_file_5.htm
File () is similar to fgets in that it reads the data one line at a time, however it returns it all at once into an array. The array contains the line number, and the data corresponding to each line number starting with 0. If you want to do more than simply echo the data, having it in an array will provide much more flexibility making file () more useful than fgets ().
<?php
$lines = file('YourFile.txt');
foreach ($lines as $line_num => $line)
{
print "<font color=red>Line #{$line_num}</font> : " . $line . "<br />\n";
}
?>
What this code does first is put the contents of YourFile.txt into the array called $lines.