php - 以表格格式显示csv数据

时间:2013-10-01 17:32:54

标签: php

我是PHP的新手,我正在尝试使用分页选项在我的网页中显示CSV数据。这是我到目前为止的代码。

<?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, 20, $page);
echo "<ul>";
while($row = $pagedResults->fetchPagedRow()) {
//when $row is false loop terminates
    $row1 = str_replace( ',', "\t", $row );
    echo "<li>{$row1}</li>";
}

echo "</ul>";

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

我在输出中显示逗号的问题。但是,我已经解决了使用str_replace函数的问题。现在,我希望以表格格式优雅地显示数据。我尝试了下面在另一个link中看到的代码。

while($row = $pagedResults->fetchPagedRow()) {
//when $row is false loop terminates
    <table>
    <tr>
    $row1 = str_replace( ',', "\t", $row );
    <td><?php echo "<li>{$row1}</li>";?></td>
    </tr>
    </table>
}

echo "</ul>";

但是,我没有在屏幕上输出。有人可以指导我朝正确的方向发展吗?

3 个答案:

答案 0 :(得分:1)

<?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, 20, $page);

echo "<table border=\"1\">";
//use the following line to manually display column names, 
//if they're not in the 1st row of the CSV file
echo "<tr><td>Column 1 name</td><td>Column 2 name</td><td>Column 3 name</td></tr>";
while($row = $pagedResults->fetchPagedRow()) {
//when $row is false loop terminates
    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();
?>

答案 1 :(得分:1)

您正在混合使用HTML和PHP。修复如下:

while($row = $pagedResults->fetchPagedRow()) {
//when $row is false loop terminates
    echo "<table>";
    echo "<tr>";
    $row1 = str_replace( ',', "\t", $row );
    echo "<td>";
    echo "<li>{$row1}</li>";
    echo "</td>";
    echo "</tr>";
    echo "</table>";
}

echo "</ul>";

或者像这样:

while($row = $pagedResults->fetchPagedRow()) {
//when $row is false loop terminates
?>
    <table>
    <tr>
    <?php $row1 = str_replace( ',', "\t", $row ); ?>
    <td><?php echo "<li>{$row1}</li>";?></td>
    </tr>
    </table><?php
}

echo "</ul>";

第一个显然具有偏好,因为它更具可读性。

答案 2 :(得分:1)

您的表格未正确放入循环中。

请参阅以下代码:

<table><?php
while($row = $pagedResults->fetchPagedRow()) {
//when $row is false loop terminates

?>
<tr>
  <?php  
    $row1 = str_replace( ',', "\t", $row );
        ?>
    <td><?php echo $row1;?></td>
        </tr>
        <?php   
}

?></table>