普通网友 2013-10-01 18:32
浏览 12

PHP - 在页面的第一页中显示两次CSV标题

I am new to PHP and trying to display the CSV data in a tabular format in my web page with pagination option. This is the code I have so far.

<?php
$names = file('demo.csv');
$page = $_GET['page'];
$pagedResults = new Paginated($names, 20, $page);
echo "<table border='2' bgcolor='#fbd998' style='float:center; margin:20'>";
//when $row is false loop terminates
while ( $row = $pagedResults->fetchPagedRow())
{
    echo "<tr><td>";
    $row1 = str_replace( ',', "</td><td>", $row );
    echo $row1;
    echo "</td></tr>";
}
echo "</table>";
//important to set the strategy to be used before a call to fetchPagedNavigation
$pagedResults->setLayout(new DoubleBarLayout());
echo $pagedResults->fetchPagedNavigation();
?>

The problem was, I was not able to display the CSV header information except the first page. To avoid this, I used the handler to extract the first line alone from CSV file (which contains the header information). I added the below piece of code before the while loop.

if (($data = fgetcsv($handle, 1000, ',')) !== FALSE)
{
}
echo "<table border='2' bgcolor='#fbd998' style='float:center; margin:20'>";
echo '<tr><th>'.implode('</th><th>', $data).'</th></tr>';

This strategy seems to be working fine in all the pages except that in the first page, I have the CSV header twice. For example, my current first page looks like below.

  • Column1 Column2 Column3
  • Column1 Column2 Column3


  • Rest of my data


Can someone please guide me on how to resolve this problem?

  • 写回答

1条回答 默认 最新

  • dongyun8891 2013-10-01 18:35
    关注

    The problem is that csv doesn't distinguish header from actual data, so the first page starts from the first row in the file and outputs it. You have to either start reading data from row nr. 2, or stop showing header at page nr. 1.

    Try changing

    echo "<table border='2' bgcolor='#fbd998' style='float:center; margin:20'>";
    echo '<tr><th>'.implode('</th><th>', $data).'</th></tr>';
    

    to this:

    if ($page != 1){
      echo "<table border='2' bgcolor='#fbd998' style='float:center; margin:20'>";
      echo '<tr><th>'.implode('</th><th>', $data).'</th></tr>';
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线