如何用PHP中的重复部分解析ini文件

时间:2015-05-27 12:55:26

标签: php arrays parsing ini

我有一个看起来像的ini文件:

[account]
user= saas
pwd=di1Z-ARMfKF2
description= as
expdate= 2015-08-22
caid = 1702,1830,0B00,0D95,0500,0648,0B02,09C7,1722,1834,098C
betatunnel= 1834.FFFF:1722,1833.FFFF:1702
group= 1,2,3,4,5,6,7,8,9,30
cccmaxhops= 5
cccreshare= 0

[account]
user= sdadsa
pwd= XnbawAH/ZYRP
description= sdasda
expdate= 2016-08-13
caid= 1702,1830,0B00,0D95,0500,0648,0B02,09C7,1722,1834,098C
betatunnel= 1834.FFFF:1722,1833.FFFF:1702
group= 1,2,3,4,5,6,7,8,9,30
cccmaxhops= 5
cccreshare= 0

我需要找到例如“user”的内容,其中描述是“sdasda”。 我试过了:

<?php
$accounts = [];
$accountIniArr = explode('[account]',   file_get_contents('oscam.user')); 
foreach ($accountIniArr as $accIni) 
{ 
$account = parse_ini_string($accIni); 
$accounts[$acc['user']] = $account; 
}
echo $accounts['sdadsa']['description'];
?>

不起作用,好像数组没有得到正确解析,任何想法如何解决?

1 个答案:

答案 0 :(得分:3)

在评论中的讨论中,您不能使用具有相同名称的ini部分,因此要使用该ini格式,您必须进行一些自定义解析。以下是chris85和Mark baker的含义示例:

$accounts = [];

// Read the .ini file contents, and explode it by the section identifier
$accountIniArr = explode('[account]', file_get_contents('users.user'));

// Iterate through the resultant array, and parse each of the user account 
// .ini settings, storing them in a multi-dimensional array as you go
for ($i=1; $i<count($accountIniArr); $i++)
{
    $accountIni = $accountIniArr[$i];
    $account = parse_ini_string($accountIni);
    $accounts[$account['user']] = $account;
}

这将产生一个包含所有帐户的多维数组,第一个索引是user字段。要使用您发布的样本数据,该数组将为:

[
 saas => [
  user => saas,
  pwd => di1Z-ARMfKF2,
  description => as,
  expdate => 2015-08-22,
  caid => 1702,1830,0B00,0D95,0500,0648,0B02,09C7,1722,1834,098C,
  betatunnel => 1834.FFFF:1722,1833.FFFF:1702,
  group => 1,2,3,4,5,6,7,8,9,30,
  cccmaxhops => 5,
  cccreshare => 0
 ],
 sdadsa => [
  user => sdadsa,
  pwd => XnbawAH/ZYRP,
  description => sdasda,
  expdate => 2016-08-13,
  caid => 1702,1830,0B00,0D95,0500,0648,0B02,09C7,1722,1834,098C,
  betatunnel => 1834.FFFF:1722,1833.FFFF:1702,
  group => 1,2,3,4,5,6,7,8,9,30,
  cccmaxhops => 5,
  cccreshare => 0
 ]
]

但是,您也可以将用户名放入ini文件部分标题而不是account