tags:

views:

143

answers:

1

Im uploading a file, and then attempting to use fgetcsv to do things to it.

This is my script below. Everything was working fine before i added the file upload portions. Now its not showing any errors, its just not displaying the uploaded data.

Im getting my "file uploaded" notice, and the file is saving properly, but the counter for number of entries is showing 0.

if(isset($_FILES[csvgo])){

    $tmp = $_FILES[csvgo][tmp_name];

    $name = "temp.csv";

    $tempdir = "csvtemp/";

    if(move_uploaded_file($tmp, $tempdir.$name)){ echo "file uploaded<br>"; }

    $csvfile = $tempdir.$name;

    $fh = fopen($csvfile, 'r');
    $headers = fgetcsv($fh);
    $data = array();
    while (! feof($fh))
    {
        $row = fgetcsv($fh);
        if (!empty($row))
        {
            $obj = new stdClass;
            foreach ($row as $i => $value)
            {
                $key = $headers[$i];
                $obj->$key = $value;
            }
            $data[] = $obj;
        }
    }
    fclose($fh);

    $c=0;

    foreach($data AS $key){

            $c++;

            $phone = $key->PHONE;

            $fax = $key->Fax;

            $email = $key->Email;

            // do things with the data here

    }

    echo "$c entries <br>";
}
A: 

You might need to specify an absolute server path.

$tempdir = $_SERVER['DOCUMENT_ROOT'] . "/csvtemp/";

Edit: I tested out your code with only a few minor modifications (the absolute path and adding quotes to your array key names) and it worked fine. Its probably something outside the scope of what you posted. Perhaps a file permissions error or something funky with the upload form.

Just a thought, but you might try raising your PHP error level. This might uncover something that had otherwise gone unnoticed.

ini_set("display_errors", 1);
ini_set("error_reporting", 2147483647);

And if that fails, you can always resort to throwing a bunch of echos all over the place until you find the culprit.

Greg W
made the change, but still nothing. No errors, nothin.
Patrick
Hm, darn. Answer updated!
Greg W
found the issue, turns out its something quirky with CSV files. I have no idea why/how, but when i open it and save it in OpenOffice Calc and save it (data is identical, checked in notepad++) it works. No idea whats going on.
Patrick
One last try for me - In that case, it might be a line ending problem. Most coding editors will have a mechanism to check what style of line ending is being used. Make sure its saved as either Unix or Windows line endings, otherwise PHP will probably fail to properly read the file. You could also try turning on auto_detect_line_endings using ini_set('auto_detect_line_endings',TRUE);
Greg W