Tuesday, April 16, 2013

Post a multi-dimension array using a single hidden input using PHP serialize

Suppose we have a 2d array:

We want to post it to report_csvD.php in HTML form.
  <form name="getcsvpdf" action="report_csvD.php" method="POST">
We can use PHP serialize function to generates a sortable representation of a value.
After post the data, we can use PHP function unserialize to change it back.
 We  had better use PHP function htmlentities  to display array in the form properly and use  html_entity_decode to change it back.
  <form name="getcsvpdf" action="report_csvD.php" method="POST"> 
    $mydata=Array();//Need to assign the value by yourself

  echo '<input type="hidden" name="mydata" value="'.$mydata_encoded.'">';

in report_csvD.php, assume the key of last column is 'dates'
header('Content-Type: application/x-excel');
header('Content-Disposition: attachment; filename="cesei_activity_log.csv"');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
 foreach($mydata as $val0)  foreach($val0 as $key=>$val){echo str_replace(',','',$val);
 if($key=='dates') echo("\n");
 else  echo(", ");}

No comments:

Post a Comment