dtby67541 2013-05-23 03:56
浏览 96
已采纳

如何读取文本并获取字符串以转换JSON文件php

I want to get some string in text file and divide then converting to JSON file this is my text file, data.txt

"5 minute input rate 134000 bits/sec, 164 packets/sec

5 minute output rate 1320000 bits/sec, 150 packets/sec"

I want get a string to array and make a JSON file maybe like this:

$time= "5 minute "
$input= "input rate 134000 bits/sec"
$output= "output rate 1320000 bits/sec"
$array[koneksi]= json_decode('[.".$time.":".$input.]');

this is my code in PHP

<?php
$lines = file('var/www/datakom/data.txt');
$title = 'data';
    foreach ($lines as $line_num => $line) {
        echo htmlspecialchars($line) . "<br />
"; }
?>

Please help me. thanks a lot

  • 写回答

2条回答 默认 最新

  • douzhaxian1267 2013-05-23 04:29
    关注

    try using a regex sth like this :

    <?php
    
    //helpfull function
    function preg_grep_keys( $pattern, $input, $flags = 0 )
    {
        $keys = preg_grep( $pattern, array_keys( $input ), $flags );
        $vals = array();
        foreach ( $keys as $key )
        {
            $vals[$key] = $input[$key];
        }
        return $vals;
    }
    
    function parseFile(){
          $pattern='/(?<time>\d+)\s+(?<time_unit>\w+)\s+(?<direction>\w+)\s+(.*?)(?<rate>\d+)\s+(?<rate_unit>\w+)(.*?)(?<packets>\d+)/i';
           $lines = file('var/www/datakom/data.txt');
           $title = 'data';
           $json_data=array();
           foreach ($lines as $line_num => $line) {
             preg_match($pattern,$line,$result);
             $json_data[]=preg_grep_keys('/time|time_unit|direction|rate|rate_unit|packets/',$result);
           }
    
        return json_encode($json_data);
    }
    
    ?>
    

    you need to invoke parseFile() function to parse the file , which will return a json "string". I am not sure you need json string or array . You can change the return statement to return json string or two-dimentional array e.g

     return json_encode($json_data);
    
     or 
    
     return  $json_data;
    

    Note: I have not tested it , please give it a try and let me know

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Pwm双极模式H桥驱动控制电机
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题