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...
   }
}

如果有人可以帮助我,我将不胜感激。

4

2 回答 2

2

发生这种情况是因为您试图像这样分解行:

; !GENERAL 包含常规设置

当你爆炸那条线时,你$data_records看起来像这样:

数组( [0] => ; !GENERAL 包含常规设置)

快速解决方案:

$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;
   }
}
于 2012-08-28T22:47:35.890 回答
0

另一种解决方案是使用正则表达式并查找!CLIENTS:部分。这也适用于 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...
    }
  }
}
于 2012-08-28T22:59:46.467 回答