Search code examples
phparraysfile-import

Push file to array in loop


EDIT after all the answers, i updated the function, and it works

I read out a importfolder. In this folder are many different files available.

  1. Step: I read the folder and add the files to a array
  2. Step: I open every file and try to import

When i cant import a file, then this happens, when another file in this row have to be imported first.

Example: If I open a file "message to a address", this could not be imported, when the address are not added into the database. But in some other file of this filelist is the "create address"-file. When this is created, then it is good, when the "message to a address" will be added to the filelistarray on the end.

My Code give me an offset problem:

function importData( $path, $db, $mail )
{
    //Get available Importfiles
    $filelist = getFilelist( $path );
    for ($i = 0; $i < count($filelist); $i++)
    {
        $filename = $path . "/" . $filelist[$i];
        $file = fopen( $filename,"r" );

        while(!feof( $file )) {
            $items = explode( ";", fgets( $file ) );

            //Get messagetyp
            if( strtolower(trim($items[0])) == "nachrichtentyp" )
            {
                $messagetyp = $items[1];
                break;
            }
        }
        fclose($file);
        if ( $messagetyp )
        {
            $f = "import" . $messagetyp;
            if( !$f($filename, $db, $mail) )
            {
                array_push($filelist, $filelist[$i]);

            }
        }
    }
}

This my error, when I push the element to the the filelist-array

PHP Warning:  feof() expects parameter 1 to be resource, boolean given in /var/www/symfony/importscript/import.php on line 37
PHP Warning:  fgets() expects parameter 1 to be resource, boolean given in /var/www/symfony/importscript/import.php on line 38

Solution

  • According to your errors, problem lies not in array_push but in fopen():

    $file = fopen( $filename,"r" );
    

    If php fails to open that file, variable $file will be set to false and because of that feof() and fgets() will give you errors.