将 HTML 表单导出到 CSV 文件测试</desc> <question vote="0"> <p>我从<a href="https://stackoverflow.com/questions/48259204/how-to-export-data-entry-in-html-form-to-csv-file">旧帖子</a>借用了一些代码来尝试实现这一目标,但它没有按预期工作。有两个问题。首先是 html:</p> <pre><code><!DOCTYPE html> <html> <title>Test Form</title> <head> </head> <body> <form name="xyz_form" action="proces.php" method="post"> <section class="border-bottom"> <div class="content"> <h3>ID Number</h3> <div class="form-control-group"> <div class="form-control form-control-number"> <input type="number" name="id_number" id="id_number"> </div> </div> <h3>First Name</h3> <div class="form-control-group"> <div class="form-control form-control-text"> <input type="text" name="first_name" id="first_name"> </div> </div> </div><!--.content--> <section class="data-capture-buttons one-buttons"> <div class="content"> <input type="submit" value="Submit"> </div> </section><!--.data-capture-buttons--> </form> </body> </html> </code></pre> <p>和 PHP 代码:</p> <pre><code><?php $fieldA = $_POST['id_number']; $fieldB = $_POST['first_name']; $keys = array($fieldA,$fieldB); $csv_line = $keys; foreach( $keys as $key ){ array_push($csv_line,'' . $_GET[$key]); } $fname = 'file_to_write_to.csv'; $csv_line = implode(',',$csv_line); if(!file_exists($fname)){$csv_line = '\r\n' . $csv_line;} $fcon = fopen($fname,'a'); $fcontent = $csv_line; fwrite($fcon,$csv_line); fclose($fcon); ?> </code></pre> <p>表单运行并写入 CSV 文件,但在运行时它会抛出两个警告:</p> <pre><code>Warning: Undefined array key 3 in E:\XAMPP\App\xampp\htdocs\test_form\proces.php on line 8 Warning: Undefined array key "Third" in E:\XAMPP\App\xampp\htdocs\test_form\proces.php on line 8 </code></pre> <p>(3 和“Third”是表格中需要的两个值。)</p> <p>现在它写入 CSV,但格式不正确。</p> <pre><code>1,First,,2,Second,,3,Third,, </code></pre> <p>它在两个值后面添加了一个额外的逗号并且无法识别 对于新线路。</p> <p>我尝试过将引号从单引号更改为双引号等。我还测试了按照原帖中的建议将第 6 行 <pre><code>$csv_line = $keys;</code></pre> 更改为 <pre><code>$csv_line = array();</code></pre>,但这并不能解决问题。</p> <p>有好心人可以帮我解决这个问题吗?谢谢。</p> </question> <answer tick="true" vote="1"> <p>@ADyson 线索是使用 <pre><code>fputcsv</code></pre> 的提示。我需要额外的参数 eol: 将默认行尾从 <pre><code>\n</code></pre> 更改为 <pre><code>\r\n</code></pre></p> <p>这是我的 PHP。</p> <pre><code><?php $fieldA = $_POST["id_number"]; $fieldB = $_POST["first_name"]; $keys = array($fieldA, $fieldB); $file_pointer = fopen("file_to_write_to.csv","a"); fputcsv($file_pointer, $keys, eol: "\r\n"); fclose($file_pointer); ?> </code></pre> </answer> </body></html>

问题描述 投票:0回答:0
php html export-to-csv
© www.soinside.com 2019 - 2024. All rights reserved.