1

I am trying to write a php script that uses checkboxes for a user to select. Once the user has selected their checkboxes my php script changes them (or is supposed to) to a CSV file. This file is then loaded from a powershell script on my local machine and is then meant to carry out the commands.

The problem I am having comes in two parts and I cant seem to find the exact answer. The first problem is the csv file that is created is in a single line. The function below sets up the csv file from the input of checkboxes however it outputs a single line csv file which I am not sure how to use.

function array_2_csv($array) {
$csv = array();
foreach ($array as $item) {
if (is_array($item)) {
    $csv[] = array_2_csv($item);
} else {
    $csv[] = $item;
}
}
return implode(',', $csv);
}

$fh = fopen("plugin.csv","w");
                fwrite($fh,$csv_data);
                fclose($fh);

The second problem I believe comes from my powershell script. Ive forced a header onto my csv file, however my switch does not seem to work. Id like to have a switch look into the array, and then execute (in this case download) some code based on what the user selected in my php file.

$selectedPlugin = Import-Csv "plugin.csv" -Header @("Plugin") 
switch($selectedPlugin.Plugin)
{ namefromCheckbox1 //code
 namefromCheckbox2 //code
}

Simply put id like the switch to download all the files that the user selected through the checkboxes earlier.

Similar to How to pass php array to local powershell script

EDIT: To answer my own question, like mentioned below my csv was returning in a single line. This was fixed by

$newCSV = explode(",",$csv_data); 

and then later

foreach($newCSV as $item) {
fwrite($fh,$item.PHP_EOL);

}

Community
  • 1
  • 1
Jingles177
  • 499
  • 2
  • 7
  • 16
  • Would you be able to post the content of a sample array? You can use var_dump($array) and post it. The thing is that, if your data is stored in a multidimensional array, it won't be easy to transform it into a CSV file, which is a flat format. You would probably be better off using XML, which is also natively supported by PowerShell. – Diego Jul 30 '12 at 22:31
  • When I use var_dump it returns: "array(2) { [0]=> string(7) "Plugin1" [1]=> string(7) "Plugin2" }" the csv file then looks like: Plugin1,Plugin2 (instead of Plugin1 Plugin2) Sample size here of course was having two checkboxes 'checked'. – Jingles177 Jul 30 '12 at 22:50
  • The CSV is definitely correct, as you used `implode()`, which joins all the entries in an array into a string, using the separator you specified. In your case, the array is `('Plugin1', 'Plugin2')` (it's not an associative array) and it becomes, as expected, `Plugin1,Plugin2`. – Diego Jul 31 '12 at 13:29

0 Answers0