【问题标题】:Read contents of multiple text files and print out specific line, in PHP在 PHP 中读取多个文本文件的内容并打印出特定的行
【发布时间】:2011-11-02 23:02:42
【问题描述】:

我们有 300 多个 txt 文件,其中基本上是电子邮件的复制品,每个 txt 文件的格式如下:

To: blabla@hotmail.com
Subject: blabla
From: bla1@hotmail.com
Message: Hello World!

目的是编写一个 PHP 脚本,它会爬取每个文件(所有文件都位于同一目录中),并在发件人字段中打印出每个“唯一”电子邮件地址的列表。这个概念很简单。

任何人都可以在这里指出正确的方向吗?到目前为止,我已经设法让我的 PHP 脚本读取目录中所有文件的内容并输出结果:

<?php
$directory = "emails/";
$dir = opendir($directory);
while (($file = readdir($dir)) !== false) {
  $filename = $directory . $file;
  $type = filetype($filename);
  if ($type == 'file') {
     $contents = file_get_contents($filename);
     $items = explode('/n', $contents);
     echo '<table width="500" border="1" cellpadding="4">';
     foreach ($items as $item) {
       echo "<tr><td>$item</td></tr>\n";
     }
     echo '</table>';
  }
}
closedir($dir);
?>

所以现在,我需要能够读取和打印每个文件的第 3 行。我假设它就像在 foreach 循环中添加数组以回显特定行一样简单?我确实尝试过这个,但从语法上讲,它有点乱:

<?php
$directory = "emails/";
$dir = opendir($directory);
**$lines = file($filename);**
while (($file = readdir($dir)) !== false) {
  $filename = $directory . $file;
  $type = filetype($filename);
  if ($type == 'file') {
     $contents = file_get_contents($filename);
     $items = explode('/n', $contents);
     echo '<table width="500" border="1" cellpadding="4">';
     foreach ($items as $item) {
       **echo "<tr><td>$lines[2]</td></tr>\n";**
     }
     echo '</table>';
  }
}
closedir($dir);
?>

谁能在这里把我推向正确的方向?

【问题讨论】:

  • 其他人可以帮忙吗??

标签: php file text


【解决方案1】:

使用命令行工具更容易做到这一点:

exec("grep '^From: ' *.txt|uniq", $output);

这将只返回所有文本文件中以From: 开头的行。一个简单的子字符串提取就可以为您提供实际的电子邮件地址,并且您为自己节省了大量的 PHP 工作。

【讨论】:

  • 我可以在什么工具中运行这个命令?我在 Windows 平台上工作。
  • 当然,只要您安装了 grep 和 uniq(几乎所有 linux/unix 发行版都存在这些)。
  • 啊。好吧,您可以在 Windows 中使用“查找”来完成其中的一些操作。不知道你用什么 uniq 虽然。
  • 嗯。现在有点困惑。我知道在 Linux 中使用直接语句要容易得多,但是我正在通过 Windows 处理 XAMMP (Apache) 实例。无论如何感谢您的帮助。
  • 您仍然可以在 windows php 中执行。你只需要找到一个相当于 grep 的 windows 版本,它是 'find' 的一个强大得多的版本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-23
  • 1970-01-01
  • 2017-07-03
  • 1970-01-01
相关资源
最近更新 更多