DEV Community

Claudio Fior for Abbrevia

Posted on

1

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay