从显示中删除CSV标题

时间:2013-10-14 19:37:07

标签: php

我正在尝试使用PHP以分页格式显示CSV文件。我正在使用HTML来显示CSV中的标题信息。我正在使用HTML,因为如果我转到其余页面,标题仍保留在表格中。但是,仅在第一页中我得到两次标题信息。我尝试使用 str_replace preg_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();

1 个答案:

答案 0 :(得分: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>";
}