fputcsv() function with SplFileObject

The SplFileObject is a replacement object oriented approach for php filesystem functions. Not all of the functions are part of the SPL classes.

fputcsv() is only available from PHP 5.4 onwards. However, it is not too hard to replicate the function if you are not using PHP 5.4. Here is how I implemented it, short and simple.


class SplFileObject extends \SplFileObject
{

    /**
     * Format line as CSV and write to file pointer.
     * This method is only available as of PHP 5.4
     *
     * @return the number of bytes written, or NULL on error.
     */
    public function fputcsv($fields, $delimiter = ',', $enclosure = '"')
    {
        array_walk($fields, function(&$value, $index, $enclosure){
            $value = $enclosure . $value . $enclosure;
        }, $enclosure);

        return $this->fwrite(utf8_encode(join($delimiter, $fields)) . "\n");
    }

}

Here is what I think is missing from the SPL file handling classes. A wrapper class is useful to manage deleting, copying, moving for file(s), and other functions that could change the location or the status of file(s).


class SplFileHandler
{

    /**
     *
     * @var SplFileObject 
     */
    protected $fileObject;

    public function copy($source, $dest)
    {
        
    }

    public function unlink()
    {
        
    }

    //... other functions to handler files
}
Posted in PHP and tagged .
Loading Facebook Comments ...

Leave a Reply

Your email address will not be published. Required fields are marked *