Parsing csv into array and displaying cells on table ERROR

57 Views Asked by At

I'm trying to get the all cells from a csv file and displaying them on a HTML table. I'm using parsecsv for getting the data, there's no problem there. However when I try to loop through array elements in order to put them into another temp array, Server stops because of memory issue. I can't see any problems with the code

    <?php

require_once('parsecsv/parsecsv.lib.php');

if (isset($_POST["submit"]))
{
    if ($_POST["row"] != "" && $_POST["column"] != "")
    {

        $column = $_POST["column"];
        $row    = $_POST["row"];

        $csv = new parseCSV();
        $csv->auto('example.csv');

        $random = array();
        foreach ($csv->data as $key => $row)
        {
            foreach ($row as $value)
            {
                array_push($random, $value);
            }
        }

        $table = <<<EOD
<style type="text/css">
table, tr, td
{
    padding: 10px;

}
    </style>
EOD;

        $table .= '<table border="1">';

        for ($i = 0; $i < $row; $i++)
        {
            $table .= '<tr>';
            for ($j = 0; $j < $column; $j++)
            {

                $table .= '<td>';
                $table .= '<p style="text-align:center;">I"m not even trying to display the data</p>';

                $table .= '</td>';
            }
            $table .= '</tr>';
        }
        $table .= '</table>';

        echo $table;

When i delete the "foreach" part it works.

Here is the error message

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 133693408 bytes) in /home/ubuntu/workspace/create_pdf.php on line 41 Call Stack: 0.0005 240672 1. {main}() /home/ubuntu/workspace/create_pdf.php:0

EDIT

When I try the same iteration in another way it works

Here is the code:

$csv = new parseCSV();
$csv->auto('example.csv');

$random = array();

foreach ($csv->data as $key => $row){
   foreach ($row as $value){
     array_push($random, $value);
   }
}

print_r($random);

?>
</pre>
<style type="text/css" media="screen">
  table { background-color: #BBB; }
  th { background-color: #EEE; }
  td { background-color: #FFF; }
  td,tr {
    padding:10px;
  }
</style>
<table border="1" cellspacing="1" cellpadding="3">
  <tr>
    <?php foreach ($csv->titles as $value): ?>
       <td><?php echo $value; ?></td>
    <?php endforeach; ?>
  </tr>
       <?php foreach ($csv->data as $key => $row): ?>
  <tr>
         <?php foreach ($row as $value): ?>
           <td><p style="text-align: center;"><?php echo $value; ?></p></td>
         <?php endforeach; ?>
  </tr>
        <?php endforeach; ?>
</table>
1

There are 1 best solutions below

1
David Keller On

You've runing the script without enough php memory. You can setup the memory_limit in the php.ini or if you are runing this as a php script you can do it as followed:

php -dmemory_limit=-1 your/script.php