是否有一种简单的方法可以解析我将在下面发布的以下数据。数据来自网络。
我使用$rows = explode("\n", $txt_file);
然后使用$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
答案 0 :(得分:1)
您可以使用trim函数来删除空格。
要仅保留所需的列,可以将其键存储在数组中,并在解析时对其进行检查。 这是一个例子(虽然相当冗长)。
<?
$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);
?>