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 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。