Anna Jeanine Anna Jeanine - 1 year ago 61
PHP Question

Read and parse a tab delimited file PHP

I worked out this Python script to read a tab delimited file and place the values where the line starts with

in a
. The code which I used for this:

import sys
from collections import OrderedDict
import json
import os

file = sys.argv[1]

f = open(file, 'r')
direc = '/dir/to/JSONs/'
fileJSON = sys.argv[1]+'.json'

key1 = OrderedDict()
summary_data = []
full_path = os.path.join(direc,fileJSON)

Read = True
for line in f:
if line.startswith("#"):
Read = True

elif line.startswith('\tC'):
Read= True

elif line.startswith('\t') and Read == True:
summary = line.strip().split('\t')
Read = True

data = json.dumps(summary_data)
with open(full_path, 'w') as datafile:

The data which I am parsing:

# BUSCO was run in mode: genome


1411 Complete BUSCOs (C)
1397 Complete and single-copy BUSCOs (S)
14 Complete and duplicated BUSCOs (D)
7 Fragmented BUSCOs (F)
22 Missing BUSCOs (M)
1440 Total BUSCO groups searched

But, I need this code in PHP.. I have managed to open the file in PHP and to read this! Could someone please help me out?

Answer Source

I didn't get the point of Read variable - it is always True in your code, the last 'elif' statement would be enough. Below is php version of your script

    $fileName = $argv[1];
    $dir = '/dir/to/JSONs/';
    $fullPath = $dir . $fileName . '.json';

    $data = [];
    $output = fopen($fileName, 'r');
    while (($line = fgets($output)) !== false) {
        if ($line[0] == "\t") {
            $summary = explode("\t", trim($line));
            if (count($summary) > 1) {
                $data[$summary[1]] = (int)$summary[0];

    $strData = json_encode([$data]);
    $input = fopen($fullPath, 'w+');
    fwrite($input, $strData);
    echo $strData;