0

我必须解析一个“有问题的”CSV 文件,如下所示:

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

当然,我只对实际包含有价值数据的行(value1、value2 和 value3)感兴趣。我试图将 url 提取到一个字符串中然后调用str_getcsv(默认参数),但我得到的是一个难以使用的数组:

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
4

1 回答 1

1

如果该结构是固定的,那么您可以制作一个行数组,然后只使用第 4 行和第 5 行。

试试这$file是一个包含您要解析的内容的变量。

$lines = array();
foreach(preg_split("/(\r?\n)/", $file) as $line){
    $lines[] = $line;
}
$data_row1 = explode(',', $lines[3]);
$data_row1 = explode(',', $lines[4]);
于 2011-10-09T14:33:20.570 回答