如何解析一个;“有问题”;PHP中的CSV
我必须解析一个“有问题”的CSV文件,如下所示:如何解析一个;“有问题”;PHP中的CSV,php,arrays,csv,fgetcsv,Php,Arrays,Csv,Fgetcsv,我必须解析一个“有问题”的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和v
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行和第5行 试试这个
$file
是一个包含要解析的内容的变量
$lines = array();
foreach(preg_split("/(\r?\n)/", $file) as $line){
$lines[] = $line;
}
$data_row1 = explode(',', $lines[3]);
$data_row1 = explode(',', $lines[4]);
这不是有效的CSV文件。您需要先解决问题(即删除无效行),然后才能对其使用fgetcsv。@ThiefMaster我知道。你认为我必须跳过开头的前两行和后面的两行吗?不是很固定,但是的,我试过了,效果很好。谢谢你的提示。有趣的是,这个无效的csv来自一个政府网站。英雄联盟