1

I'm just trying to upload a csv file and convert it to an array.

I've read on a previous post here that you can use str_getcsv() without having to physically upload the csv file to the server.

Is this correct or do I have to store the file somewhere first before I can run str_getcsv() and then delete it afterwards?

Here's my simple code at the moment (I'm using php 5.3):

if (isset($_POST['file_upload'])){
    $csv = str_getcsv($_POST['csvfile']);

echo '<pre>';
print_r($csv);
echo '</pre>';
}
2
  • 2
    you obviously have to upload the file since u cant access it otherwise, but you dont have to save the uploaded file, it will be uploaded into the php tmp folder and deleted after your script is finished Commented Aug 8, 2013 at 11:39
  • Ahh, I was not aware of the tmp directory at all. I'll look into that now. Commented Aug 8, 2013 at 11:41

3 Answers 3

2

You should use $_FILES array to check file upload.
Use this code:

if(isset($_FILES["csvfile"])) {
    $csv=str_getcsv(file_get_contents($_FILES["csvfile"]["tmp_name"]));

    echo '<pre>';
    print_r($csv);
    echo '</pre>';
}
Sign up to request clarification or add additional context in comments.

1 Comment

Absolutely perfect, thank you so much! Before I started this I never realised it was so easy to do.
0

By default the file is stored in a temp directory which can be accessed by $_FILES['file_name']['tmp_name']:

As you can see, the first parameter of str_getcsv method must be a string and for this you can use file_get_contents

$csv = str_getcsv(file_get_contents($_FILES['csvfile']['tmp_name']));

Comments

0

If you are submitting a file (using <input type="file">), you will need to use move_uploaded_file(). The file is already on disk (if the form submit was succesful), you just need to move it. In this case, it is most convenient to use fgetcsv() which opens the file and parses it into arrays as you go (see the example in the documentation for that function).

If you are not submitting a file but a text using, for example, <textarea></textarea>, then you do not have to write the string in the $_POST variable to disk but can use str_getcsv to parse the string into an array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.