Tuesday, April 16, 2013

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



Suppose we have a 2d array:
 <?php
     $mydata=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.php
  <form name="getcsvpdf" action="report_csvD.php" method="POST"> 
 <?php
    $mydata=Array();//Need to assign the value by yourself

   $mydata_s=serialize($mydata);    
   $mydata_encoded=htmlentities($mydata_s);
  echo '<input type="hidden" name="mydata" value="'.$mydata_encoded.'">';
?> 
</form>

in report_csvD.php, assume the key of last column is 'dates'
<?php
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');
$mydata=unserialize(html_entity_decode($_POST['mydata']));
 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