php / php/php-src

str_getcsv won't work correctly in some special cases

Open
#10,566 6 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Extension: standard Status: Needs Triage
Dominant language
C
Stars
40.4k
Forks
8.1k
Avg merge
2d 13h
Merged PRs (30d)
96

Description

Description

The function should not rebuild the string-annotation in the CSV-String by using the commas, if str_getcsv is used in the first step of the small algorithm.
The following code is motivated by the example of durik at 3ilab dot net : He mentioned: "...
Why not use explode() instead of str_getcsv() to parse rows? Because explode() would not treat possible enclosured parts of string or escaped characters correctly."

<?php

$string =<<<DOMTEST
"PHP, Java","Python"
"PHP2, Java2","Python"
"PHP3, Java3","Python"
DOMTEST;

  $data = str_getcsv($string, "\n" );
        foreach ($data as &$row) {
            $row = str_getcsv($row, ',');
        }
var_dump($data);

Resulted in this output:

array(3) {
  [0]=>
  array(3) {
    [0]=>
    string(3) "PHP"
    [1]=>
    string(5) " Java"
    [2]=>
    string(6) "Python"
  }
  [1]=>
  array(3) {
    [0]=>
    string(4) "PHP2"
    [1]=>
    string(6) " Java2"
    [2]=>
    string(6) "Python"
  }
  [2]=>
  &array(3) {
    [0]=>
    string(4) "PHP3"
    [1]=>
    string(6) " Java3"
    [2]=>
    string(6) "Python"
  }
}

But I expected this output instead:

array(3) {
  [0]=>
  array(2) {
    [0]=>
    string(8) "PHP, Java"
    [1]=>
    string(6) "Python"
  }
  [1]=>
  array(2) {
    [0]=>
    string(10) "PHP2, Java2"
    [1]=>
    string(6) "Python"
  }
  [2]=>
  &array(2) {
    [0]=>
    string(10) "PHP3, Java3"
    [1]=>
    string(6) "Python"
  }
}
PHP Version

8.2.1

Operating System

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the supplied PHP example using str_getcsv with newline and comma delimiters, then inspect the function's existing behavior for quoted commas and escaped characters. The issue does not name an implementation file or test; done means the intended nested parsing behavior is established and covered by regression testing.

Written by the indexing model from the issue text.

Assessment

Tech stack
php
Domain
backend-api-design
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.