0

I am trying to display a CSV file in a paginated format using PHP. I am using HTML to display the header information from CSV. I am using HTML because if I go to the remaining pages, the header remains in the table. However, in the first page alone I get the header information twice. I tried to remove it using str_replace and preg_replace but to no luck. This is the code I have so far.

<?php
$names = file('demo.csv');
$page = $_GET['page'];

//constructor takes three parameters
//1. array to be paged
//2. number of results per page (optional parameter. Default is 10)
//3. the current page (optional parameter. Default  is 1)
$pagedResults = new Paginated($names, 50, $page);
$handle = fopen('demo.csv', 'r');
  if (($data = fgetcsv($handle, 1000, ',')) !== FALSE)
    {
    }

echo "<table id='kwTable' border='4' bgcolor='#adb214' style='float:center; margin:100'>";
echo '<tr><th>'.implode('</th><th>', $data).'</th></tr>';
?>
<tbody id="kwBody">
<?php
//when $row is false loop terminates
while ( $row = $pagedResults->fetchPagedRow())
{
    echo "<tr><td>";
    //echo '<tr><th>'.implode('</th><th>', $data).'</th></tr>';
    //Here I am getting the header information from the CSV file twice. 
    $row1 = str_replace( ',', "</td><td>", $row );
    echo $row1;
    echo "</td></tr>";
}
fclose($handle);
echo "</table>";

//important to set the strategy to be used before a call to fetchPagedNavigation
$pagedResults->setLayout(new DoubleBarLayout());
echo $pagedResults->fetchPagedNavigation();
4

1 回答 1

1

如果您在 CSV 顶部只有一个标题行,那么您只需要在第一次通过时跳过该行:

$header = true;
if (!$page) $page = 1;
while ( $row = $pagedResults->fetchPagedRow())
{
    if ($page == 1 && $header) {
        $header = false;
        continue;  // Skip this header row
    }
    echo "<tr><td>";
    //echo '<tr><th>'.implode('</th><th>', $data).'</th></tr>';
    //Here I am getting the header information from the CSV file twice. 
    $row1 = str_replace( ',', "</td><td>", $row );
    echo $row1;
    echo "</td></tr>";
}
于 2013-10-14T19:41:59.500 回答