Managing Data Conversions I
Learn how to work with data formatting by using fixed-width data schemes.
This chapter will explore techniques and methods for working with data formatted using fixed-width data schemes. Fixed-width data formats are one of those development items that do not come up that often when working on typical web applications, but when they do, they can completely take some developers off guard. This is not because working with these formats is inherently tricky; and it is just that it is quite different from typical day-to-day tasks.
It will be challenging to discuss this topic in terms of absolutes or provide a meaningful generalized solution for reading and writing fixed-width data. The way data is encoded when stored in a fixed-width format highly depends on the application used to do the storage and the schema or data definition used among other things. However, we can look at a few techniques together to understand how to work with this type of data.
Let’s consider the table below, which contains some sample invoice data:
Sample Invoices
Invoice # | Total | Quantity | Product ID |
1 | 12.00 | 5 | 1 |
2 | 32.32 | 1 | 2 |
3 | 16 | 10 | 3 |
4 | 622 | 4 | 4 |
5 | 77 | 1 | 5 |
Our table contains a handful of sample invoice data. From left to right, we have the invoice number, the total amount of currency charged for the invoice, the amount of product purchased, and finally, a product identifier. We do not know much about this data, such as the actual data types. For our sample invoices, we will assume that all values, except for the total, are integers; our total is a decimal number.
Example of fixed-width data
Let’s now assume that we have received the following text file:
1 12 5 12 32.32 1 23 16 10 34 622 4 45 77 1 5
When we compare this code to the table shown above, we can quickly see how the data is associated. Each table row is represented as a single line within our text file, and each cell is stored within 10 characters. Our first task will be to generate our text file from the following PHP array:
<?php$invoices = [['number' => 1,'total' => 12.0,'quantity' => 5,'pid' => 1,],['number' => 2,'total' => 32.32,'quantity' => 1,'pid' => 2,],['number' => 3,'total' => 16.0,'quantity' => 10,'pid' => 3,],['number' => 4,'total' => 622.0,'quantity' => 4,'pid' => 4,],['number' => 5,'total' => 77.0,'quantity' => 1,'pid' => 5,],];
Let’s think about how we can convert our array into the format we saw in the figure above. It is at this point that it is easy to overcomplicate things. We have already encountered the tools we need to perform our task through the Laravel ...