duan198811 2014-05-22 22:24
浏览 54
已采纳

php - 显示.txt文件中每行的第一项

I have a .txt file which contains lines that follow a standard convention. I can read every line of the .txt file into an array, but I can't split the spaces in each line and put each word into a new array in order to list the first item of each line.

Access.txt

2014-03-16 13:57:35.089 -0700 Information 98
2014-03-16 13:57:35.089 -0700 Information 22
2014-03-16 13:57:35.355 -0700 Information 638
2014-03-16 13:57:35.355 -0700 Information 94

LogsModel:

public function fileGetContents()
{
    $filename = 'C:/Program Files/FileMaker/FileMaker Server/Logs/Access.log';

    // Open the file
    $fp = @fopen($filename, 'r');

    // Add each line to an array
    if ($fp) {
        $lines = explode("
", fread($fp, filesize($filename)));

        // split each line by " "
        foreach($lines as $line){
            $line_items = explode(" ", $line);

            return $line_items;
        }
    }
}

LogsController:

public function index()
{
    // load a model, perform an action, pass the returned data to a variable
    $logs_model = $this->loadModel('LogsModel');
    $line_items = $logs_model->fileGetContents();


    // load views.
    require 'application/views/_templates/header.php';
    require 'application/views/home/index.php';
    require 'application/views/_templates/footer.php';
}

home/index.php

<table class="table table-striped">
    <tr>
        <td>Date</td>
    </tr>
    <?php foreach ($line_items as $item) { ?>
        <tr>
            <td><?php echo $item ?></td>
        </tr>
    <?php } ?>
</table>

Right now I'm getting ALL the items from the first line...

DATE
2014-03-16
13:57:35.089
-0700   
Information 
98

What I want to display is the first item from EACH line...

DATE
2014-03-16
2014-03-16
2014-03-16
2014-03-16
  • 写回答

3条回答 默认 最新

  • duanbamo0127 2014-05-22 22:30
    关注

    Its pretty simple:

      $line_items = explode(" ", $lines[0]); //split first line
      echo $line_items[0]; //print first item
    

    If you only want one item of one line, why is your method called fileGetContents()? You're trying to return the whole file as one line, constantly in a loop. Won't work. You need to redesign this method.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退