【问题标题】:Output from CSV import in PHP functionPHP函数中CSV导入的输出
【发布时间】:2018-02-18 14:36:54
【问题描述】:

我在 PHP 中有一个函数,它使用 CSV 文件中的数据创建一个 HTML 表。

问题是每个表的标题被打印两次。首先是<th>,然后是第一个<tr>。我希望标题只打印在<th> 中,而不是在下面的<tr> 中。 错误是什么,您对 PHP 函数有其他建议吗?

csv 示例

title a, Titel A 
example1, Beispiel1
example2, Beispiel2

title b, Titel B
example1, Beispiel1
example2, Beispiel2

php函数

function CreateLangTable($csvFile, $startRow, $endRow, $number) {
    global $lang_code1, $lang_code2, $vocabulary_group, $urlArray;

    if ($endRow < $startRow) {
        return;
    }
    echo ' 
  <a id="' . $vocabulary_group[$urlArray[4]][$number] . '"></a>  
 <div class="table-responsive">  
  <table class="table table-hover table-bordered table-striped table-fixed">                           
    <thead class="blue-grey lighten-4">';
    $csvFile->seek($startRow);
    vprintf('
        <tr>  
          <th><div data-text="%1$s" data-lang="' . $lang_code1 . '" class="trigger_play"> %1$s</div></th> 
          <th><div data-text="%2$s" data-lang="' . $lang_code2 . '" class="trigger_play"> %2$s</div></th>
        </tr>
    </thead>
    <tbody>', $csvFile->current());
    while ($csvFile->key() <= $endRow) {
    vprintf('   
        <tr>
          <td><div data-text="%1$s" data-lang="' . $lang_code1 . '" class="trigger_play"> %1$s</div></td> 
          <td><div data-text="%2$s" data-lang="' . $lang_code2 . '" class="trigger_play"> %2$s</div></td>
        </tr>', $csvFile->current());
 $csvFile->next();              
    }

    echo '
    </tbody>
  </table>
</div>' . "\n";
}
if ($urlArray[3] == "vokabeln" &&  isset($urlArray[4])) { // Undefined offset: 3 [only until /url1/url2/]
    $file = new SplFileObject($_SERVER['DOCUMENT_ROOT'] . "/$urlArray[1]/csv/$urlArray[4].csv");
    $file->setFlags(SplFileObject::READ_CSV);
}

用于生成此 CSV 示例的 HTML 表格的 php 代码:

CreateLangTable($file, 0, 2, 0);
CreateLangTable($file, 4, 6, 1);

【问题讨论】:

    标签: php html csv import


    【解决方案1】:

    $csvFile-&gt;seek($startRow); 行获取指向标题的指针。
    然后while ($csvFile-&gt;key() &lt;= $endRow) 从同一点开始循环。 在'while()'之前应该有一个$csvFile-&gt;next();
    那是
    $csvFile-&gt;next();
    while ($csvFile-&gt;key() &lt;= $endRow) {...}

    【讨论】:

      猜你喜欢
      • 2019-12-12
      • 1970-01-01
      • 1970-01-01
      • 2021-12-31
      • 2016-02-05
      • 2017-10-03
      • 2011-01-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多