csv 为什么我的Php不创建一个不存在的文件

b5buobof  于 5个月前  发布在  PHP
关注(0)|答案(1)|浏览(78)

我试图让我的php创建一个文件与正确的索引的数据和头部在顶部的CSV与数据输入的索引就在下面,目前我可以有数据输入到CSV时,头部已经在文件和文件已经存在.我怎么才能使它这样它创建的文件自动在选定的目录.

<?php
if (isset($_POST['submit'])) {
    // Collect the form data.
    $fileName = dirname(__DIR__ . '/..') . "ModuleData" . ".csv";
    $file = new SplFileObject($fileName, 'r');
    $file ->seek(PHP_INT_MAX);
    $index = $file -> key();
    $moduleCode = isset($_POST['module-code']) ? $_POST['module-code'] : '';
    $moduleName = isset($_POST['module-name']) ? $_POST['module-name'] : '';
    $lecturer = isset($_POST['lecturer']) ? $_POST['lecturer'] : '';
    $semYear = isset($_POST['SemYear']) ? $_POST['SemYear'] : '';

    // Check if module code is set.
    if ($moduleCode == '') {
        $errors[] = 'Module code required';
    }

    // Validate the module name.
    if ($moduleName == '') {
        $errors[] = 'Please enter a valid module name';
    }

    // Validate the lecturer name.
    if ($lecturer == '') {
        $errors[] = 'Please enter a valid lecturer name';
    }

    // Validate the semester year.
    if ($semYear == '') {
        $errors[] = 'Please enter a valid date';
    }

    // If no errors, carry on.
    if (!isset($errors)) {
        // The header row of the CSV.
        $header = "index,moduleCode,moduleName,lecturer,semYear\n";
        // The data row of the CSV.
        $data = "$index,$moduleCode,$moduleName,$lecturer,$semYear\n";

        // Create or append to the CSV file.
        $file = fopen($fileName, 'a+');
        if ($file) {
            // If the file exists, append the data.
            fwrite($file, $data);
            fclose($file);
            echo 'success';
        } else {
            // If the file doesn't exist, create it and add the header and data.
            $file = fopen($fileName, 'w');
            if ($file) {
                fwrite($file, $header . $data);
                fclose($file);
                echo 'success creating file';
            } else {
                echo 'failed to create file';
            }
        }
    }
}

字符串
这就是我目前所拥有的。

vlju58qv

vlju58qv1#

我可以看到三个问题:

  1. 'a+'打开阅读和写入;将文件指针放在文件的末尾。如果文件不存在,尝试创建它。
    此标志将自动创建不存在的文件。由于fopen返回false,这意味着您传递的路径有问题。
  2. dirname()对输入字符串进行简单的操作,并且不知道实际的文件系统或路径组件,例如“.."。
    因此dirname(__DIR__ . '/..')的结果等同于__DIR__。如果你想获取当前文件的父目录,你应该用途:
dirname(__DIR__)

字符串
1.dirname():否则,返回的字符串为删除了所有尾随/组件的path。
除了根目录,dirname的返回结果不包含结尾斜杠。所以这个dirname(....) . "ModuleData"很可能是一个错误的路径,需要添加分隔符:

dirname(__DIR__) . DIRECTORY_SEPARATOR . "ModuleData"

相关问题