问题
I'm sort of new to PHP, and I need some help on exploding data from a file. The file in question is: http://data.vattastic.com/vatsim-data.txt
Basically, I need to get the data under the !CLIENTS:
section (near the bottom). With this data, I need to explode it and get the info between each :
.
I have tried with this code, but it gives me a variable offset error (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...
}
}
If someone could help me with this, I'd greatly appreciate it.
回答1:
This happens because you are trying to explode rows like this:
; !GENERAL contains general settings
When you explode that line, you your $data_records
looks like this:
Array ( [0] => ; !GENERAL contains general settings )
Quick solution:
$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;
}
}
回答2:
Another solution is to use regular expressions and look for !CLIENTS:
section. This would also work in the case that the CLIENTS have more or less than 42 columns in the future
$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...
}
}
}
来源:https://stackoverflow.com/questions/12168543/grab-and-explode-data