Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If the csv data is in a file, you can just use fgetcsv() as others have pointed out. fgetcsv handles embedded newlines correctly.</p> <p>However if your csv data is in a string (like $fileData in your example) the following method may be useful as str_getcsv() only works on a row at a time and cannot split a whole file into records.</p> <p>You can detect the embedded newlines by counting the quotes in each line. If there are an odd number of quotes, you have an incomplete line, so concatenate this line with the following line. Once you have an even number of quotes, you have a complete record.</p> <p>Once you have a complete record, split it at the quotes (again using explode()). Odd-numbered fields are quoted (thus embedded commas are not special), even-numbered fields are not.</p> <p>Example:</p> <pre><code># Split file into physical lines (records may span lines) $lines = explode("\n", $fileData); # Re-assemble records $records = array (); $record = ''; $lineSep = ''; foreach ($lines as $line) { # Escape @ symbol so we can use it as a marker (as it does not conflict with # any special CSV character.) $line = str_replace('@', '@a', $line); # Escape commas as we don't yet know which ones are separators $line = str_replace(',', '@c', $line); # Escape quotes in a form that uses no special characters $line = str_replace("\\'", '@q', $line); $line = str_replace('\\', '@b', $line); $record .= $lineSep . $line; $lineSep = "\n"; # Must have an even number of quotes in a complete record! if (substr_count($record, "'") % 2 == 0) { $records[] = $record; $record = ''; $lineSep = ''; } } if (strlen($record) &gt; 0) { $records[] = $record; } $rows = array (); foreach ($records as $record) { $chunks_in = explode("'", $record); $chunks_out = array (); # Decode escaped quotes/backslashes. # Decode field-separating commas (unless quoted) foreach ($chunks_in as $i =&gt; $chunk) { # Unescape quotes &amp; backslashes $chunk = str_replace('@q', "'", $chunk); $chunk = str_replace('@b', '\\', $chunk); if ($i % 2 == 0) { # Unescape commas $chunk = str_replace('@c', ',', $chunk); } $chunks_out[] = $chunk; } # Join back together, discarding unescaped quotes $record = join('', $chunks_out); $chunks_in = explode(',', $record); $row = array (); foreach ($chunks_in as $chunk) { $chunk = str_replace('@c', ',', $chunk); $chunk = str_replace('@a', '@', $chunk); $row[] = $chunk; } $rows[] = $row; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload