PHP错误调用未定义的函数,如何给出一个方法数据使用

时间:2017-05-16 12:26:04

标签: php csv phpexcel

我正在构建一个脚本,它从/ uploads文件夹中获取每个xls文件并将其转换为CSV。

但是,我遇到了这个错误:

  

致命错误:
  未捕获错误:在C:\ xampp \ htdocs \ Technocripa-php \ scandir.php中调用未定义函数convertXLStoCSV():46堆栈跟踪:#0 {main}在C:\ xampp \ htdocs \ Technocripa-php \ scandir中引发。第46行的PHP

以下是代码:

$dir = "uploads/*";
foreach(glob($dir) as $file)
{
    if(!is_dir($file)) { echo basename($file)."\n";}
    //--------------------------

    $nameAsString = (string)$file;

    require_once('Classes/PHPExcel.php');

    $inputfilename = $nameAsString;
    $outputfilename = 'convert.csv';

    //Usage:
    convertXLStoCSV($inputfilename, $outputfilename);

    function convertXLStoCSV($infile, $outfile)
    {
        $fileType = PHPExcel_IOFactory::identify($infile);
        $objReader = PHPExcel_IOFactory::createReader($fileType);

        $objReader->setReadDataOnly(true);
        $objPHPExcel = $objReader->load($infile);

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
        $objWriter->save($outfile);
    }
}

我认为错误来自错误的变量用法,但我真的找不到解决这个问题的方法。我想要的是将te文件的名称存储在变量的uploads /文件夹中,并在整个脚本中使用它。

这是没有LOOP的程序,它没有任何错误。也许有助于更好地理解。

require_once('Classes/PHPExcel.php');

  $inputfilename = 'test2.xls';
  $outputfilename = 'convert.csv';

  //Usage:
  convertXLStoCSV($inputfilename, $outputfilename);

  function convertXLStoCSV($infile, $outfile)
  {
      $fileType = PHPExcel_IOFactory::identify($infile);
      $objReader = PHPExcel_IOFactory::createReader($fileType);

      $objReader->setReadDataOnly(true);
      $objPHPExcel = $objReader->load($infile);

      $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
      $objWriter->save($outfile);
  }

2 个答案:

答案 0 :(得分:2)

foreach之外创建函数,并在下面调用它:

function convertXLStoCSV($infile, $outfile)
{
    $fileType = PHPExcel_IOFactory::identify($infile);
    $objReader = PHPExcel_IOFactory::createReader($fileType);

    $objReader->setReadDataOnly(true);
    $objPHPExcel = $objReader->load($infile);

    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
    $objWriter->save($outfile);
}

$dir = "uploads/*";
foreach(glob($dir) as $file)
{
    if(!is_dir($file)) { echo basename($file)."\n";}
    //--------------------------

    $nameAsString = (string)$file;

    require_once('Classes/PHPExcel.php');

    $inputfilename = $nameAsString;
    $outputfilename = 'convert.csv';

    //Usage:
    convertXLStoCSV($inputfilename, $outputfilename);


}

答案 1 :(得分:1)

    function convertXLStoCSV($infile, $outfile)
    {
        $fileType = PHPExcel_IOFactory::identify($infile);
        $objReader = PHPExcel_IOFactory::createReader($fileType);

        $objReader->setReadDataOnly(true);
        $objPHPExcel = $objReader->load($infile);

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
        $objWriter->save($outfile);
    }

convertXLStoCSV($inputfilename, $outputfilename);

在使用它之前声明该函数