从显示中删除 CSV 标头


Remove the CSV header from display

我正在尝试使用 PHP 以分页格式显示 CSV 文件。我正在使用 HTML 来显示来自 CSV 的标题信息。我正在使用 HTML,因为如果我转到其余页面,标题会保留在表中。但是,仅在第一页中,我就获得了两次标题信息。我试图使用str_replacepreg_replace将其删除,但没有运气。这是我到目前为止的代码。

<?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();

如果您在 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>";
}