0

有没有一种简单的方法来解析我将在下面发布的以下数据。数据来自网络。

我使用$rows = explode("\n", $txt_file);then$parts = explode('=', $line_of_text);来获取键名和值。但是,我不知道如何处理我不想要的额外信息。

此外,我不知道如何摆脱多余的空间。该文件似乎是为某种简单的解析而制作的。我查看了整个网站以找到解决方案。但是,此数据与我在此站点上找到的示例完全不同。

# This file holds all the timelines available at this time.
# All lines starting with # is ignored by parser...
#

STARTINFO
description     =       Rubi-Ka 2
displayname     =       Rimor (Rubi-Ka 2)
connect         =       cm.d2.funcom.com
ports           =       7502
url             =       
version         =       18.5.4
ENDINFO

STARTINFO
description     =       Rubi-Ka 1
displayname     =       Atlantean (Rubi-Ka 1)
connect         =       cm.d1.funcom.com
ports           =       7501
url             =       
version         =       18.5.4
ENDINFO
4

1 回答 1

1

您可以使用修剪功能摆脱空白。

为了只保留您想要的列,您可以将它们的键存储在一个数组中,并在解析时对其进行检查。这是一个示例(尽管相当冗长)。

<?
$lines = explode("\n", $data);
$result = array();
$count = 0;
// an array of the keys we want to keep
// I have the columns as keys rather then values for faster lookup
$cols_to_keep = array( 'url'=>null, 'description'=>null, 'ports'=>null, 'displayname' => null);

foreach($lines as $line)
{
  //skip comments and empty lines
  if(empty($line) || $line[0] == '#')
  {  continue; }

  //if we start a new block, initalize result array for it
  if(trim($line) == 'STARTINFO')
  {
    $result[$count] = array();
    continue;
  }

  // if we reach ENDINFO increment count
  if(trim($line) == 'ENDINFO')
  {
    $count++;
    continue;
  }

  //here we can split into key - value
  $parts = explode('=', $line);

  //and if it's in our cols_to_keep, we add it on
  if(array_key_exists(trim($parts[0]), $cols_to_keep))
  { $result[$count][ trim($parts[0]) ] = trim( $parts[1] );  }
}
print_r($result);
?>
于 2013-02-14T14:59:09.827 回答