从PHP中的位置文本文件中读取内容?

时间:2014-10-08 09:16:22

标签: php file fseek

我的文本文件格式如下

00151422    N8X 3V6 2013-11-11 00:19:00.000 IN          patricksoong@hotmail.com                    E       200-2462 Howard Avenue      Windsor ON  CAN N8X3V6  M   Dr. Patrick Soong

00331448    T6E 2R1 2010-03-01 00:00:00.000 IN          atirlea@yahoo.com                   E       9743 88 Ave NW      Edmonton    AB  CAN T6E2R1      Alina Tirlea Engstrom

00364578    K7N 1A3 2011-01-12 00:00:00.000 IN                              E       4463 Bath Rd        Amherstview ON  CAN K7N1A3  M   Mr. Martin Kandler



上述位置文本文件在每条记录中包含3条记录和20个字段。我现在每列的大小。我将如何使用PHP在记录中读取记录和字段?

字段大小

F1 = 8; F 2 = 10; F3 = 10; F4 = 10; F5 = 255; F6 = 50; F7 = 255; F8 = 10; F9 = 10; F10 = 50; F11 = 50; F12 = 1 ; F13 = 20; F14 = 50; F15 = 50; F16 = 60; F17 = 10; F18 = 20; F19 = 20; F20 = 1;

2 个答案:

答案 0 :(得分:2)

在某种循环中使用substr()。未经测试,但应该给你一个想法:

$lengths = [8,10,10]; // define all the lengths

function fixed_width_data_to_array($data, $lengths) {

    foreach($rows as $row) {

        $position = 0; // start at the beginning of the row

        foreach($lengths as $length) {

            // add current field to array
            $my_data[] = trim(substr($row, $position, $length)); 

            // move the 'pointer' to the start of the next field
            $position += $length; 
        }

        // add current row to an array
        $my_array[] = $my_data;

     }

     return $my_array;

}

答案 1 :(得分:-1)

谢谢sal00m,终于得到了答案 - 使用标签爆炸。