简体   繁体   中英

How to parse a “problematic” CSV in PHP

I've to parse a "problematic" CSV file like this:

some text here
other line of text, here
header1, header2, header3
value1, value2, value3  // data row #1
value1, value2, value3  // data row #2
(empty line)
(empty line)
some other text here

Of course i'm only interested in rows (value1, value2 and value3) that actually contains valuable data. I've tried to fetch the url into a string and than call str_getcsv (default parameters) but what i'm getting is an array that is difficult to work with:

array
  0 => string 'some text here ' (length=50)
  1 => string ' other text here
other text here
header1 ' (length=50)
  2 => string 'header2' (length=13)
  3 => string 'header3' (length=14)
  4 => string 'header4' (length=14)
  5 => string '
value1' (length=2)
  6 => string 'value2' (length=1)
  7 => string 'value3' (length=1)
  8 => string 'value4

If that structure is fixed, then you could make an array of lines and then just use the 4th and 5th line.

Try this $file is a variable with the content you want to parse.

$lines = array();
foreach(preg_split("/(\r?\n)/", $file) as $line){
    $lines[] = $line;
}
$data_row1 = explode(',', $lines[3]);
$data_row1 = explode(',', $lines[4]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM