【问题标题】:PHP: Parse Error in script importing csv dataPHP:在导入 csv 数据的脚本中出现解析错误
【发布时间】:2015-12-09 10:00:17
【问题描述】:

我创建了这个小脚本来解析一个 cvs 文件,然后将它传递给 mysql。我需要对其进行一些编辑,但我刚刚开始根据http://csv.thephpleague.com 手册编辑日期格式。

<?php

    if (!ini_get("auto_detect_line_endings")) {
        ini_set("auto_detect_line_endings", '1');
    }

    use League\Csv\Reader;

    $reality = Reader::createFromPath('Workbook3.csv');
    $planed = Reader::createFromPath('Workbook4.csv');

    /*this function removes the "First name" "Second name" elements and 
    creates one that actually has the entier name in capital*/
    $functionHRT = function ($row) {
        $row['hrtData'] => DateTimeImmutable::createFromFormat($row['Contract Start'], 'd-m-Y'); /*this is line 18*/
    }

    $hrtData = $reality
                // ->setOffset(7);
                ->fetchAssoc( , $functionHRT());
    $hrtData[0]['Contract Start']->format('Y-m-d');        

    ?>

当我尝试运行它时,我得到一个:

Parse error: parse error in /Users/nefeli/Code/ph/script.php on line 18

错误代码。我不确定问题语法错误是什么。对此有何见解?

【问题讨论】:

    标签: php mysql csv import-from-excel


    【解决方案1】:

    此行有语法错误:

    $reality->fetchAssoc( , $functionHRT());
    

    根据docs,这是方法的签名:

    fetchAssoc($offset_or_keys = 0, callable $callable = null)

    所以,如果你想传递回调,你还必须指定函数的第一个参数。您可以使用默认值 (0) 并将回调作为第二个参数传递。

    还请记住,当您传递回调时,您不必调用它(使用括号就像您正在做的那样),但您只需要指定变量,因为您之前已声明 lamba function并将其存储在$functionHRT 变量中

    所以你的电话应该是:

    $reality->fetchAssoc( 0, $functionHRT );
    

    语句中还有一个错误:

    $functionHRT = function ($row) {
        $row['hrtData'] => DateTimeImmutable::createFromFormat($row['Contract Start'], 'd-m-Y'); /*this is line 18*/
    }
    

    您使用错误的运算符为数组赋值。应该是:

    $functionHRT = function ($row) {
        $row['hrtData'] = DateTimeImmutable::createFromFormat($row['Contract Start'], 'd-m-Y'); /*this is line 18*/     
    };
    

    您还需要在回调声明的末尾添加一个分号

    【讨论】:

    • 非常感谢您的关注!你对解析错误有什么想法吗?
    • @Byte_Monster:在 PHP 中,只有当函数参数具有默认值 并且 排在最后时,才能省略它们。 fetchAssoc(, $callback) 因此是不可能的。您必须填写第一个参数。 fetchAssoc()fetchAssoc(1)fetchAssoc(0, $callback) 是可能的。其次,您不要在回调中添加括号。
    • 非常感谢我解决了这个问题。但是请稍等片刻,因为我在使用英雄联盟时一定犯了一个错误。我按照 Docks 的建议运行作曲家 $ composer require league/csv 但现在我收到错误:Fatal error: Class 'League\Csv\Reader' not found in /Users/me/Code/script.php on line 12 我在 Mac 操作系统上,作曲家确实运行正确。我的语法有问题吗?
    • 实际上我发现了问题:我没有使用 include 'vendor/autoload.php'; 。非常感谢人们!这非常有用。
    • @Byte_Monster :要接受答案,您应该点击向上/向下投票箭头下的“复选标记”:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-28
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    • 2015-11-20
    • 1970-01-01
    相关资源
    最近更新 更多