2012-08-28 32 views
0

我对PHP很陌生,我需要一些关于从文件中爆炸数据的帮助。有问题的文件是:http://data.vattastic.com/vatsim-data.txt抓取和分解数据

基本上,我需要得到的数据下!CLIENTS:部分(底部附近)。有了这些数据,我需要将其爆炸并获取每个:之间的信息。

我曾尝试与此代码,但它给了我一个可变的偏移误差(Undefined offset: 3

$file = file("http://data.vattastic.com/vatsim-data.txt"); 
foreach($file as $line) 
{ 
    $data_record = explode(":", $line); 

    // grab only the data that has "ATC" in it... 
    if($data_record[3] == 'ATC' && $data_record[16] != '1' && $data_record[18] != '0'&& stristr($data_record[0],'OBS') === FALSE) 
    { 
     rest of code here... 
    } 
} 

如果有人能帮助我,我会非常感激。

+0

使用'var_dump($ data_record)'。问题是'$ data_record'没有第三个位置 – Gerep

+0

'var_dump($ data_record)'正在返回数据文件中的所有内容。在“!客户端”部分获取这些内容的最佳方法是什么? – Dutchcoffee

+0

看起来像'explode(“:”,$ line);'没有返回你所期望的。您应该在尝试访问它们之前测试'$ data_record'是否具有正确数量的元素 – peacemaker

回答

2

这是因为你正试图爆炸这样行:

; !一般包含一般设置

当爆炸那行,你的$data_records看起来是这样的:

阵列(! [0] =>;一般包含一般设置)

快速解决方案:

$file = file("http://data.vattastic.com/vatsim-data.txt"); 
foreach($file as $line) 
{ 
    if(strpos($line,';') === 0) continue ; // this is comment. ignoring 
    $data_record = explode(":", $line); 
    $col_count = count($data_record); 

    switch($col_count) { 
    case 42: // columns qty = 42, so this is row from `clients` 
     // grab only the data that has "ATC" in it... 
     if($data_record[3] == 'ATC' && $data_record[16] != '1' && $data_record[18] != '0'&& stristr($data_record[0],'OBS') === FALSE) 
     { 
      rest of code here... 
     } 
     break; 
    default: 
     // this is other kind of data, ignoring 
     break; 
    } 
} 
+0

这似乎很好。我会再测试一下,让你知道。 – Dutchcoffee

+0

似乎一切工作,因为它应该。谢谢你的帮助! – Dutchcoffee

0

另一种解决方案是将u请输入正则表达式并查找!CLIENTS:部分。这也适用于客户未来有多于或少于42列的情况

$file = file_get_contents ("http://data.vattastic.com/vatsim-data.txt"); 
$matches = null; 
preg_match ('/!CLIENTS:\s\n(.*)\n;/s' , $file, $matches); 
if($matches) 
{ 
    $client_lines = explode("\n", $matches[1]); 
    foreach ($client_lines as $client) 
    { 
    $data_record = explode(":", $client); 
    if($data_record[3] == 'ATC' && $data_record[16] != '1' && $data_record[18] != '0'&& stristr($data_record[0],'OBS') === FALSE) 
    { 
     //rest of code here... 
    } 
    } 
} 
+0

我的正则表达式技巧并不好,但尝试过,工作正常,但也许有更好的REGEX来解决这个 –

+0

我会记住你的代码,以防列数发生变化。谢谢! – Dutchcoffee