草庐IT

PHP fgetcsv() 分隔符 ';' 无法识别

coder 2024-04-13 原文

看来我对“;”有疑问定界符。这是我的 csv 文件:

First Name;Last Name;Email;Age
Julie;Brown;julie@example.com;52
Dan;Wong;dan@example.com;19
Tim;Hortons;tim@example.com;27

和我的 PHP 代码:

$row = 1;
if (($handle = fopen("upload/".$_FILES['fichier']['name'], "r")) !== FALSE) {
    while (($data = fgetcsv($handle, ";")) !== FALSE) {
        $num = count($data);
        echo "<p> $num champs à la ligne $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
fclose($handle);
}

我有这个输出:

1 champs à la ligne 1: 
First Name;Last Name;Email;Age
1 champs à la ligne 2: 
Julie;Brown;julie@example.com;52
1 champs à la ligne 3: 
Dan;Wong;dan@example.com;19
1 champs à la ligne 4: 
Tim;Hortons;tim@example.com;27

当我使用','分隔符时,而不是像这样

4 champs à la ligne 1: 
First Name
Last Name
Email
Age

此外,我想知道是否可以有各种分隔符。因为我想显示用户上传的 csv 文件,我不想强​​迫他们使用一个预定的分隔符。

谢谢

最佳答案

第二个参数是长度,所以你的fgetcsv应该是

fgetcsv($handle, 0, ';');

导致

4 champs à la ligne 1: 

First Name
Last Name
Email
Age
4 champs à la ligne 2: 

Julie
Brown
julie@example.com
52
4 champs à la ligne 3: 

Dan
Wong
dan@example.com
19
4 champs à la ligne 4: 

Tim
Hortons
tim@example.com
27

关于你的第二个关于变量定界符的问题。到目前为止,最简单的方法是允许用户定义要在上传表单上使用的分隔符,可能使用可接受分隔符的选择元素,然后在读取 csv 时使用它。

例如

function filter_delimiter($v) {
    return in_array($v, [',', ';'], true) ? $v : null;
}

//validate $_POST['delimiter'];
$delimiter = filter_input(INPUT_POST, 'delimiter', FILTER_CALLBACK, ['options' => 'filter_delimiter']);
if (!$delimiter) {
    $delimiter = ';';
    //optionally redirect to form error message
}

或者解析行以确定适当的分隔符。

$filename = "upload/".$_FILES['fichier']['name'];
if (($handle = fopen($filename, "r")) !== false) {
    $content = fread($handle, filesize($filename));
    fclose($handle);
    //count the delimiters
    $semiColons = substr_count($content, ';');
    $commas = substr_count($content, ',');
    //read each row
    $rows = str_getcsv($content, "\n");
    $rowCount = count($rows);
    $delimiter = null;
    foreach ($rows as $line => $row) {
        //check the delimiters
        if (false === isset($delimiter)) {
            /* 
              determine if the delimiter total divided by the number 
              of rows matches the delimiters found on this row 
              and use it to parse the columns 
            */
            if ($semiColons > 0 && $semiColons / $rowCount === substr_count($row, ';')) {
                $delimiter = ';';
            } elseif ($commas > 0 && $commas / $rowCount === substr_count($row, ',')) {
                $delimiter = ',';
            }
        }
        //read the columns using the detected delimiter 
        //otherwise use a default if a delimiter could not be determined
        $columns = str_getcsv($row, $delimiter ? : ';');
        echo "<p>$rowCount champs à la ligne " . ($line + 1) . "</p>\n";
        foreach ($columns as $column) {
            echo $column . "<br/>\n";
        }
    }
}

关于PHP fgetcsv() 分隔符 ';' 无法识别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37748133/

有关PHP fgetcsv() 分隔符 ';' 无法识别的更多相关文章

  1. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  2. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  3. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  4. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  5. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  6. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  7. ruby - 在 jRuby 中使用 'fork' 生成进程的替代方案? - 2

    在MRIRuby中我可以这样做:deftransferinternal_server=self.init_serverpid=forkdointernal_server.runend#Maketheserverprocessrunindependently.Process.detach(pid)internal_client=self.init_client#Dootherstuffwithconnectingtointernal_server...internal_client.post('somedata')ensure#KillserverProcess.kill('KILL',

  8. ruby-on-rails - 无法在centos上安装therubyracer(V8和GCC出错) - 2

    我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e

  9. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  10. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

随机推荐