使用php将CSV转换为HTML表格

问题描述 投票:1回答:1

我正在尝试从我的CSV文件中获取数据并使用php在html表中显示它,按客户姓氏排序。我尝试了几件事情似乎并没有起作用。

我得到的输出是:enter image description here现在格式是最后,第一,地址,城市,区,邮政编码如何使用PHP将其导入到html表?

使用此代码。

if( ($handle = fopen( 'input.csv', 'r' )) !== false )
{
    $output = '<table>';
    while( ($data = fgetcsv( $handle )) !== false )
    {
        $output .= '<tr>';
        foreach( $data as $value )
        {
            $output .= sprintf( '<td>%s</td>', $value );
        }
        $output .= '</tr>';
    }
    fclose( $handle );
    $output .= '</table>';
}
echo $output;
php csv html-table
1个回答
1
投票

在您的上一条评论中,您要求表头,以便您可以编写如下代码,

echo '<table border="1">';
echo '<thead>';
echo '<tr>';
echo '<th>last</th>';
echo '<th>first</th>';
echo '<th>address</th>';
echo '<th>.....</th>';
echo '<th>......</th>';
echo '<th>.....</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';

    while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
        $num = count($data);
        echo '<tr>';

        for ($c=0; $c < $num; $c++) {
            if(empty($data[$c])) {
               $value = "&nbsp;";
            } else {
               $value = $data[$c];
            }                
            echo '<td>'.$value.'</td>';

        }
        echo '</tr>';

        $row++;
    }

    echo '</tbody></table>';
© www.soinside.com 2019 - 2024. All rights reserved.