如何将txt文件转换为数组

时间:2017-04-04 12:00:53

标签: php

我在txt文件上有这种结构。

[FILE_INFO]
[FIRST]
LOAD1= CPU
LOAD2 = RAM     
[END_FIRST]
[GLOBAL_INDEX]
ELEC1=1235.12
GAZ2,1=1563.123
GAZ2,2= 28.56
[END_GLOBAL_INDEX]
[END_FILE_INFO]

我需要的是将这个txt结构转换为php数组,这是可能的还是txt结构?

Array
(
    [FILE_INFO] => Array
        (
            [FIRST] => Array
                (
                    [LOAD1] => CPU
                    [LOAD2] => RAM
                )

            [GLOBAL_INDEX] => Array
                (
                    [ELEC1] => 1235.12
                    [GAZ2] => Array
                        (
                            [1] => 1563.123
                            [2] => 28.56
                        )

                )

        )

)

这是我的方法:

$txt_file    = file_get_contents("test.rt");
$rows = explode("\n", $txt_file);
$new_array = array(); $dimension = array();
    foreach($rows as $row =>$data)
    {       
        if($data[0] == "[" && substr($data, 0, 4) != "[END"){ // start
            $output = str_replace( array('[',']') , ''  , $data );
            array_push($dimension, trim($output));
            continue;       
        }else if(substr($data, 0, 4) == "[END"){ // end
            $output = str_replace( array('[',']') , ''  , $data );
            array_pop($dimension);
            continue;           
        }   
        $dim="";
        foreach($dimension as $k=>$v){
            $dim.= "['$v']";
        }
        $new_array.$dim[] = $data; // this is not working !!!!!
    }

问题是将光标定位在数组的维度中并插入数据

1 个答案:

答案 0 :(得分:0)

试试这个:

<?php
$myfile = fopen("test.txt", "r");
// Iterate one line until end-of-file
while(!feof($myfile)) {
    $text[] = fgets($myfile);  // Add the data in an array
}
fclose($myfile);
print_r($text);  // print the array
?>