基于CSV文件在HTML中自动构建表+不能得到可能的解决方案


automatically build a table in html based on a csv file + can't get possible solution to work

我在这里找到了这个解决方案

但我不能让它工作,但它可能是一些基本的,谁能建议吗?

这是PHP在我的服务器上的样子:

$ cat table.php
<?php
echo "<html><body><table>'n'n";
 = fopen("temp.csv", "r");
while (( = fgetcsv()) !== false) {
        echo "<tr>";
        foreach ( as ) {
                echo "<td>" . htmlspecialchars() . "</td>";
        }
        echo "</tr>'n";
}
fclose();
echo "'n</table></body></html>";

CSV文件是这样的:

$ cat temp.csv
DeviceName,counter1,counter2,counter3,counter4
DeviceName1,85%,87%,75%,63%
DeviceName2,85%,85%,74%,70%
DeviceName3,80%,81%,70%,66%
DeviceName4,78%,82%,70%,74%
DeviceName5,77%,75%,68%,58%
DeviceName6,77%,72%,66%,58%

然后进入浏览器的地址

webaddressgoeshere/php/table.php

我在控制台上得到以下内容:

GET webaddressgoeshere/php/table.php 500 (Internal Server Error)
Navigated to webaddressgoeshere/php/table.php

我的答案下面,我错过了一个变量,当我复制和粘贴。哎呀! !

$ cat table.php
<?php
echo "<html><body><table>'n'n";
$f = fopen("temp.csv", "r");
while (($line = fgetcsv($f)) !== false) {
        echo "<tr>";
        foreach ($line as $cell) {
                echo "<td>" . htmlspecialchars($cell) . "</td>";
        }
        echo "</tr>'n";
}
fclose($f);
<?php
if($csv_fp = fopen('csv_file.csv','r'))
{
    echo '<table>';
    while ($data = fGetCsv ($csv_fp, 8096, ","))
    {
        // you can view the array $data holds by print_r($data); exit();
       echo '<tr>';
       foreach($data as $d)
       {
            echo '<td>'.$d.'</td>';
       }
    echo '</tr>';
    }
   echo '</table>';
}
else
{
   echo 'Failed to open file';
}

看起来你的代码有一些语法问题。代码是不完整的。下面是代码:

<?php
echo "<html><body><table>'n'n";  
$xfile = fopen("temp.csv", "r");  // variable was missing
while (( $line = fgetcsv($xfile)) !== false) {   // here too
         echo "<tr>";
         foreach ( $line as $ value) {   // and here
                 echo "<td>" . htmlspecialchars($value) . "</td>";    // and here
         }
         echo "</tr>'n";
}
fclose($xfile);   // and here
echo "'n</table></body></html>";
?>