Monday, 2 February 2015

Convert Fixed Width To Array

Convert Fixed Width To Array

Following on from a recent posting a request was recieved to convert a fixed width file into an array. The process is quite similar to creating a class as the file is iterated over and the array of positions and widths are used to build the array. In this example, the SplFileObject and SPL CachingIterator are used to traverse each line of the file, and then the fixedWidthToArray() function takes care of the business of creating an array of fields from each line.
The text file used in this example looks like this
bill smith      1 jones st        Australia
paul jones      2 smith st        New Jersey
sid snot        4 The Win         London

EXAMPLE


<?php

    error_reporting
E_ALL );

    
/**
    *
    * Create array based on fixed width file
    *
    * @param    string  $string The string of fixed width fields
    * @param    array   $fields The array of fieldnames and widths
    * @return       array
    *
    */
    
function fixedWidthToArray$string$fields )
    {
        
$ret = array();
        foreach( 
$fields as $fieldname => $widths )
        {
            
$ret[$fieldname] = trimsubstr$string$widths[0], $widths[1] ) );
        }
        return 
$ret;
    }



    
$fields = array(
            
'name'=>array( 010 ),
            
'address'=>array( 1020 ),
            
'city'=>array( 3015 )
            );

    
/*** a new SPL file object ***/
    
$file_object =  new cachingIterator( new SplFileObject'file.txt' ) );

    
$array = array();
    foreach( 
$file_object as $line )
    {
        if( 
$file_object->hasNext() )
        {
            
$array[] = fixedWidthToArray$file_object->current(), &$fields );
        }
    }

    
print_r$array );?>

DEMONSTRATION

Array
(
    [0] => Array
 (
     [name] => bill smith
     [address] => 1 jones st
     [city] => Australia
 )

    [1] => Array
 (
     [name] => paul jones
     [address] => 2 smith st
     [city] => New Jersey
 )

    [2] => Array
 (
     [name] => sid snot
     [address] => 4 The Win
     [city] => London
 )

)

0 comments:

Post a Comment