Search code examples
phpfgetcsv

Supressing fgetcsv warning


I have the following function to get a csv file form a third party resource:

    public function getSubject()
    {       
        $file   =  fopen( $this->url , 'r');
        $result = array();
        while ( ( $line = fgetcsv( $file )) !== false ) {
            if ( array(0 => null) !== $line ) {
                $result[] = $line;
            }
        }

        fclose( $file );
        $this->setSubject( $result );
    }

The problem arises when the third party csv file is unavailable, I get this error:

PHP Warning: fgetcsv() expects parameter 1 to be resource, boolean given in /var/www/html/code.php on line 57

What is the best way to test for this error?


Solution

  • Test $file after you open it.

    $file = fopen($this->url, 'r');
    if (!$file) {
        die("Unable to open URL");
    }