I want to fetch all the contents of a csv file into an array so I used the fgetcsv function. It is working correctly, but when I want to return my array it is empty. The problem seems to be outside the while loop.

Here is my code:

$filepath="Data\";
$csvfile=array();    /* here i did declaration */

$csvfile=csvcontain($filepath);
print_r($csvfile);  /*prints empty array */

function csvcontain($filepath)
{
    foreach (glob($filepath."*."."csv") as $filename) 
    {
        $file_handle = fopen($filename, 'r');
        while (!feof($file_handle)) 
        {
            $csv=fgetcsv($file_handle, 1024);
            $csvfile=$csv;
        }
    }
    fclose($file_handle);
    return $csvfile;
}

I am not getting where it is going wrong.

有帮助吗?

解决方案

csvfile is being overwritten, not added to on each iteration of the loop.

Try replacing $csvfile=$csv; with $csvfile[]=$csv;. This should add a new element to an array.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top