PHP从文本文件解析文本区域

时间:2015-05-18 16:09:59

标签: php parsing text-files

我有一个具有以下结构的文本文件:

[account]
user                          = heinz
pwd                           = heinz123
description                   = ralf
caid                          = 098C,1702,1830,0B00,0D95,0648,0500,0B02,09C4
expdate                       = 2015-06-30
au                            = 1
group                         = 1,2,3,4,5,6,7,8,9,30
cccmaxhops                    = 5
cccreshare                    = 0
cccignorereshare              = 1

[account]
user                          = klaus
pwd                           = klaus123
caid                          = 098C,1702,1830,0B00,0648,0D95,0500,09C4
description                   = sven
au                            = 1
betatunnel                    = 1833.FFFF:1702
expdate                       = 2015-06-30
group                         = 1,2,3,4,5,6,7,8,9,30
services                      = !xxl
cccmaxhops                    = 5
cccreshare                    = 1
cccignorereshare              = 1

[account]
user                          = paul
pwd                           = paul123
description                   = ralf
caid                          = 1702,1830,0B00,0D95,0648,0500,0B02,098C
betatunnel                    = 1833.FFFF:1702
expdate                       = 2015-06-30
group                         = 1,2,3,4,5,6,7,8,9,30
cccmaxhops                    = 5
cccreshare                    = 0
cccignorereshare              = 1

现在举例来说,我需要获得描述为“sven”的“user”字段。这应该返回“克劳斯”。知道如何使用PHP轻松完成这项工作吗?每个用户块以“[account]”开头,以“cccignorereshare = 1”结尾。

1 个答案:

答案 0 :(得分:0)

假设您的文件内容已加载到var $content中。这将完成工作并指出您正确的方向从内容字符串/文件中获取其他信息。

// Build array
$accounts = array();
$tmpAccounts = explode( "[account]", $content );
foreach ( $tmpAccounts as $data ) {
    $tmpLines = explode( "\n", $data );
    $parsedData = array();
    foreach ( $tmpLines as $line ) {
        list( $key, $value ) = explode( "=", $line );
        $parsedData[trim( $key )] = trim( $value );
    }
    $accounts[] = $parsedData;
}

// Find 'sven' as description in array
$user = '';
foreach ( $accounts as $account ) {
    if ( $account['description'] == 'sven' ) {
        $user = $account['user'];
    }
}

// Output
echo( $user );

另一种方法是使用某种正则表达式。但上面的代码应该可以完成这项工作。