I have a little php code that queries a database and then writes the record to a flat text file. Works fine. But I have it comma delimited... after each field it inserts a comma.

I need to have this fixed width. In other words, can PHP somehow know how long the field is in the DB, and write out the data that is in the field, and also pad the rest with spaces if needed?

Or will I have to check each line and determine the length, and if it's not a certain length will I have to write the number of spaces needed to fill it all out? That sounds like a pain in the rear.

Thanks.

    You can use strlen to figure out how long a string is. But, you'll still need some logic to know how many spaces to add. You could collect all the lines together with their length. Then determine which one is the longest. And add spaces to all the others based on the difference.

      Hmm interesting, still sounds like a pain. Each field in the database is not the same length. They vary between 2 and 50. So I guess I'd have to read the field, determine how long the data itself is, then write it to the file along with any additional spaces needed for that field.

        It will be a "pain" as you definitely need more code logic, but it's not that much more.

        // Code sample
        // Function that will add spaces to a str
        function addSpaces($intNumOfSpaces) {
            $i=0;
            $output='';
            while ($intNumOfSpaces!=$i) {
                $output.=" "; // possibly need  
                $i++;
            }
            return $output;
        }
        
        // $lines is an array of all the lines you need to output.
        // Get $line_lengths, and $longest_line
        $longest_line = 0;
        for ($i=0;$i<count($lines);$i++) {
            $line_lengths[$i]=strlen($lines[$i]);
            if ($line_lengths[$i] > $longest_line) $longest_line = $line_lengths[$i];
        }
        
        // Add spaces to $lines
        for ($i=0;$i<count($lines);$i++) {
            if ($line_lengths[$i]==$longest_line) {
                // No spaces needed
                echo $lines[$i];
            } else {
                // Add spaces
                echo $lines[$i].addSpaces($longest_line-$line_lengths[$i]);
            }
        }
        

        Would it be possible to store the line length in the database? That would take out the need for one of the loops.

          Write a Reply...