I have been struggling with this...
I need to post to a php page to create a csv file. The problem is, I can not figure out how to create a proper array and then to post it to the php to process.
My php page has a function that iterates through the posted value and writes to the csv.
function outputCSV($data) {
$output = fopen("php://output", "w");
foreach ($data as $row) {
fputcsv($output, $row);
}
fclose($output);
}
I am getting the $data
through a post like so...
$csvData = $_POST['csvData'];
Then running the function...
outputCSV($csvData);
When I post, I get the error Warning: Invalid argument supplied for foreach()
I know it has something to do with my arrays in the original (post from) page, or how I am sending it.
Here is how the array should be formatted (which works if I set it up in the php page then run the function)
outputCSV(
array(
array("name 1", "age 1", "city 1"),
array("name 2", "age 2", "city 2"),
array("name 3", "age 3", "city 3")
)
);
Now, on my post-from page, I am looping through some values and building a variable var newData = [];
which consists of an array with arrays as values, when I print in the console, I get this...
Array [ Array[3], Array[3], Array[3] ]
To me, this looks correct, but I am having the hardest time passing this variable to the php page to be proccess correctly.
I have tried many things, like setting an input value with the variable, then posting.
<input id="csv" name="csvData[]"/>
$('#csv').val(newData);
I have tried using jquery's $.post
like so
$.post("csvsave.php",{'csvData': newData});
Plus a bunch of other ways though I would only be wasting your time listing them out as I think either of the above two ways should work and I might be missing something simple.
Sometimes I get an incomplete result (like just one array) with php's print_r
, other times I get all the values in the csv but in just one line, but it always throws the error I mentioned above, and even sometimes writes the error to the csv page.
I'm so frazzled right now that any help or guidance would be greatly appreciated. Thank you in advance! James
ADDITION
If I do a var_dump
on the posted value, I get this
array(1) { [0]=> string(59) "name 1,age 1,city 1,name 2,age 2,city 2,name 3,age 3,city 3" }
For some reason I am losing the inner arrays
var_dump
on$_POST['csvData']
? Obviously it's not a normal array if it's saying invalid arg. – Noah Matisoff Oct 28 '14 at 4:04array(1) { [0]=> string(59) "name 1,age 1,city 1,name 2,age 2,city 2,name 3,age 3,city 3" }
the thing is if Iconsole.dir()
the variable on the first page I getArray [ Array[3], Array[3], Array[3] ]
looks like I can not pass the inner arrays – VIDesignz Oct 28 '14 at 4:08