update page now

Voting

: max(nine, seven)?
(Example: nine)

The Note You're Voting On

ivijan dot stefan at gmail dot com
5 years ago
Imagine a situation where you need a function that works with both URL and comma delimited text.

This is exactly the function that works like that using str_getcsv(). Just simply insert a CSV URL or comma separated text and it work nicely.

<?php
function parse_csv( $filename_or_text, $delimiter=',', $enclosure='"', $linebreak="\n" )
{
    $return = array();
    
    if(false !== ($csv = (filter_var($filename_or_text, FILTER_VALIDATE_URL) ? file_get_contents($filename_or_text) : $filename_or_text)))
    {
        $csv = trim($csv);
        $csv = mb_convert_encoding($csv, 'UTF-16LE');   
        
        foreach(str_getcsv($csv, $linebreak, $enclosure) as $row){
            $col = str_getcsv($row, $delimiter, $enclosure);
            $col = array_map('trim', $col);
            $return[] = $col;
        }
    }
    else
    {
        throw new \Exception('Can not open the file.');
        $return = false;
    }
    
    return $return;
}
?>

<< Back to user notes page

To Top