【问题标题】:Reading content from positional text file in PHP?从 PHP 中的位置文本文件中读取内容?
【发布时间】:2014-10-08 09:16:21
【问题描述】:

我有以下格式的文本文件

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;f2=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;

【问题讨论】:

  • 为什么不直接explode 进行迭代?
  • 文件中没有分隔符。
  • 字段不受制表符限制?不是,您应该要求您的提供商向您发送一个 CSV 文件,以逗号或制表符分隔...或其他内容,否则您需要使用 substr 解析它
  • 让我试着通知你。 :)
  • 谢谢哥们,工作正常。 :)

标签: php file fseek


【解决方案1】:

在某种循环中使用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;

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-13
    • 2011-03-23
    • 1970-01-01
    • 1970-01-01
    • 2013-03-18
    相关资源
    最近更新 更多