How to save a CSV file to a variable with a foreach loop?
Basically, I am loading a CSV file via a HTML upload form, then saving it
into PHP. I need to create a foreach loop to somehow print out the file
line by line.
I am not to sure how to do this since I have honestly never designed a PHP
foreach loop before.
This is the code that is capturing and saving the multidimensional array
from the CSV file
$csv_array = array(array());
$file = fopen($_FILES['upload_csv']['tmp_name'], 'r');
if($file)
{
while (($line = fgetcsv($file)) !== FALSE)
{
$csv_array[] = array_combine(range(1, count($line)),
array_values($line));
}
fclose($file);
}
This is my current foreach loop which is not working well at all which I
grabbed and slightly changed from one of my other functions.
$all_questions;
if(!empty($csv_array))
{
foreach($csv_array as $question)
{
$all_questions = $all_questions . implode(',',$question) . "\n";
}
}
So in conclusion, I need my foreach loop to go through my multidimensional
array to save it as one big string. If my CSV file is like this:
question1,answer1,answer2,answer3,answer4
question2,answer1,answer2,answer3,answer4
question3,answer1,answer2,answer3,answer4
I need it saved into a variable in the exact same format. I need to also
keep my multidimensional array since I need it for other reasons.
Thanks in advance!
No comments:
Post a Comment