Showing posts with label PHP feof. Show all posts
Showing posts with label PHP feof. Show all posts

Friday, 2 August 2019

PHP function used to read CSV files

The below function can be used to read CSV files and returning an array with all values obtained from the CSV file
USAGE:
Copy the below function to your PHP script
function readCSV($csvFile){
 
 
        $file_handle = fopen($csvFile, 'r');
 
        while (!feof($file_handle) ) {
 
                $line_of_text[] = fgetcsv($file_handle, 1024);
 
        }

Monday, 23 February 2015

PHP: Generate CSV file from a PHP array

Here is a simple but efficient function to generate a .csv file from a PHP array. The function accept 3 parameters: the data, the csv delimeter (default is a comma) and the csv enclosure (default is a double quote).
<?php
function generateCsv($data, $delimiter = ',', $enclosure = '"') { 
$handle = fopen('php://temp', 'r+'); 
foreach ($data as $line) { 
fputcsv($handle, $line, $delimiter, $enclosure);
 } 
rewind($handle); 
while (!feof($handle)) { 
$contents .= fread($handle, 8192); 
}
 fclose($handle); 
return $contents; 
}
?>

Saturday, 4 October 2014

feof in PHP

feof — Tests for end-of-file on a file pointer
Syntax:

bool feof ( resource $handle )
Tests for end-of-file on a file pointer.

Parameters:

handle
The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

Return values: Returns TRUE if the file pointer is at EOF or an error occurs (including socket timeout); otherwise returns FALSE.



Warning
If a connection opened by fsockopen() wasn't closed by the server, feof() will hang. To workaround this, see below example:
Example #1 Handling timeouts with feof()
<?php
function safe_feof($fp, &$start = NULL) {
 $start = microtime(true);

 return feof($fp);
}

/* Assuming $fp is previously opened by fsockopen() */

$start = NULL;
$timeout = ini_get('default_socket_timeout');

while(!safe_feof($fp, $start) && (microtime(true) - $start) < $timeout)
{
 /* Handle */
}
?>
Warning
If the passed file pointer is not valid you may get an infinite loop, because feof() fails to return TRUE.
Example #2 feof() example with an invalid file pointer
<?php
// if file can not be read or doesn't exist fopen function returns FALSE
$file = @fopen("no_such_file", "r");

// FALSE from fopen will issue warning and result in infinite loop here
while (!feof($file)) {
}

fclose($file);
?>