将txt解析为json

时间:2017-09-18 18:36:42

标签: php json parsing

我有一个看起来像这样的txt文件:

1 - 10
2 - 20
3 - 30

如何制作看起来像这样的json数组:

{
  "item": "1",
  "value": "10"
},

{
  "item": "2",
  "value": "20"
},

{
  "item": "3",
  "value": "30"
},

谢谢!

3 个答案:

答案 0 :(得分:1)

您需要从文本文件中逐行读取并使用分隔符' - '展开该行。然后创建一个可以转换为json的数组。

// Open the file to read data.
$fh = fopen('student.txt','r');
// define an eampty array
$data = array();
// read data
while ($line = fgets($fh)) {
    // if the line has some data
   if(trim($line)!=''){
       // explode each line data 
       $line_data = explode('-',$line);
       // push data to array
       //array_push($data,array('item'=>trim($line_data[0]),'value'=>trim($line_data[1])));
       $data[]=array('item'=>trim($line_data[0]),'value'=>trim($line_data[1]));
   }
}
fclose($fh);
// json encode the array
echo $json_data = json_encode($data);

输出:

[{"item":"1","value":"10"},
{"item":"2","value":"20"},
{"item":"3","value":"30"}]

答案 1 :(得分:0)

#include file with data
$arg = file('text.txt');

#create array for our json
$res = [];

#start the cycle
foreach ($arg as $k => $v) {

    #convert string to array.
    $arr[] = explode(' - ', $v);

    #take first element
    $res[$k]['item'] = current($arr[$k]);

    #take second element and cut wrapp with (int)
    $res[$k]['value'] = (int)next($arr[$k]);
}

#option "JSON_PRETTY_PRINT" for displaying the format text
$res = json_encode($res, JSON_PRETTY_PRINT);

#print result
echo '<pre>';
print_r($res);
echo '</pre>';

我们的结果

[
    {
        "item": "1",
        "value": 10
    },
    {
        "item": "2",
        "value": 20
    },
    {
        "item": "3",
        "value": 30
    },
    {
        "item": "5",
        "value": 33
    },
    {
        "item": "4",
        "value": 3534
    }
]

答案 2 :(得分:0)

另一种方法解决方案::

<?php

// the list in the txt file 
$str = "1 - 10
        2 - 20
        3 - 30";


$so = explode(" ", $str);



$cleanedvalues = array();

foreach ($so as $key => $value) {
    if ($value != "") {
        $cleanedvalues[] = $value;
    }
}


$arrval = array();

foreach ($cleanedvalues as $key => $value) {
    if ($value == "-") {

    } else {
        $arrval[] = $value;
    }
}



$tab_keys   = array();
$tab_values = array();
foreach ($arrval as $key => $value) {
    if ($key % 2 == 0) {
        $tab_keys[] = $value;
    } else {
        $tab_values[] = $value;
    }

}

// add the item and value data 
$lan = array();
for ($i = 0; $i < sizeof($tab_keys); $i++) {
    $lan[] = array(
        'item' => trim($tab_keys[$i]),
        'value' => trim($tab_values[$i])
    );
}

// the final result 
echo json_encode($lan);
?>