Re: Delete first line of a csv file if it is the headers

From: Date: Mon, 30 Apr 2007 04:22:56 +0000
Subject: Re: Delete first line of a csv file if it is the headers
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-254130@lists.php.net to get a copy of this message
Richard Kurth wrote:
     The below script will parse a csv file to a database I need to remove
the first line because it is the header files and I don't need them. How can I test for that and remove them. $file = fopen($_POST['copy'], 'r') or $message .= "Could not open" . $_POST[copy] . "for reading.<BR>\n";
                while (!feof($file)){
You don't need this loop. fgetcsv will do it for you (see the example at http://php.net/fgetcsv
                    # We could easily be importing 10,000 records.  Give us
some time here, okay?
                    set_time_limit(30);
and you're setting this with every line in the file.. probably not what you intended. From the php page but slightly modified: $row = 0; $handle = fopen("test.csv", "r"); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $row++;
    if ($row == 1) {
        echo "Found headers, skipping\n";
        continue;
    }
    $num = count($data);
    echo "<p> $num fields in line $row: <br />\n";
} <snip>
                            if ($fieldname == 'notes'){
                                $notes .= addslashes("$field\n");
If you're putting this into a database you should look to use the relevant _escape_string functions (eg mysql_real_escape_string or pg_escape_string) because they handle quotes & character sets a lot smarter than addslashes does.
                                # Note that file data is not Magic-Quoted:
                                $$fieldname = addslashes($field);
Same here. -- Postgresql & php tutorials http://www.designmagick.com/

« previous php.general (#254130) next »