DEV Community

Claudio Fior for Abbrevia

Posted on

Data in fixed fields text files

I have to read and write data from a fixed fields text file.
What is a it? It'a mess like this.

Fixed fields text file

The data organized based on the character position:
1 - 11 Packet ID
12 - 11 Anagraph ID
23 - 10 Submission date
and so on.

How can I read the data in PHP?

First, ugly solution: use substr to read

 $identificativo_pacchetto = substr($line,0,11);
 $identificativo_mandante = substr($line,11,11);
 $data_affido = substr($line,22,10);
...
Enter fullscreen mode Exit fullscreen mode

and str_pad to write

 $line = str_pad($identificativo_pacchetto,11);
 $line .= str_pad($identificativo_mandante,11);
 $line .= str_pad($data_affido,10);
...
Enter fullscreen mode Exit fullscreen mode

It'a nightmare!!!

Lets'try with unpack and pack command.

One line of code to read.

$data =unpack('A11identificativo_pacchetto/A11identificativo_mandante/A10data_affido',$line));

Enter fullscreen mode Exit fullscreen mode

and data is an array like this

{
   "identificativo_pacchetto":"1",
   "identificativo_mandante":"52301",
   "data_affido":"19-11-2021"
}
Enter fullscreen mode Exit fullscreen mode

One line of code to write

$data = ['1','52301','19-11-2021'];
$line =pack('A11A11A10',...$data));

Enter fullscreen mode Exit fullscreen mode

The is no need to pad the values.
Note that the are no filed names (eg . identificativo_pacchetto) and no separators (/).

I put all together defining the structure in an array.

$def = [
'A11identificativo_pacchetto',
'A11identificativo_mandante',
'A10data_affido
];
$data = ['1','52301','19-11-2021'];
$line = pack(implode('',preg_replace('/^(A\d+).*/','$1',$def)),...$data);
$data = unpack(implode('/',$def),$line);
Enter fullscreen mode Exit fullscreen mode

More info:
PHP manual
PHP Cookbook
Stackoverflow

Top comments (0)