PHP; assigning fgets() output to an array

筅森魡賤 提交于 2019-12-12 03:59:48

问题


I am attempting to assign the string returned by the fgets() function to an array in PHP. I have tried test strings and they work fine. I have also made sure that fgets() is returning items, but still no joy. Thinking that it may be a timing issue, I had the function run onload and that didn't work. My code is below; any help on this would be much appreciated.

function createDataArray()
    {
        global $resultsArray;

        $i = 0;
        $file = fopen("downloads/E0.csv","r");

        while(! feof($file))
        {
            $line = fgets($file, 4096);
            $resultsArray[$i] = $line; //This isn't working. Something is wrong with $line. It is a string, but it doesn't get assigned to the array.
            $i = $i + 1;
        }
        fclose($file);
    }

回答1:


PLEASE return the array; do not use globals.

This fix should work:

function createDataArray()
    {
        $resultsArray = array();

        $file = fopen("downloads/E0.csv","r");

        while(! feof($file))
        {
            $line = fgets($file, 4096);
            $resultsArray[] = $line; 
        }
        fclose($file);

        return $resultsArray;
    }


来源:https://stackoverflow.com/questions/8479672/php-assigning-fgets-output-to-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!