读取一个大文本文件并将选定的行复制到另一个文件

时间:2013-05-22 05:50:19

标签: php file text fopen

我需要从here创建一个数据库表:

因此,我使用curl命令将同一文件复制到服务器文件夹。我需要从上面的文本文件中检索00-00-00 (hex) XEROX CORPORATION, 00-00-01 (hex) XEROX CORPORATION等。我只需要将十六进制值和第一行组织复制到另一个文本文件。

我该如何使用PHP?

3 个答案:

答案 0 :(得分:2)

  <?php
  // open the input and the output
  $fp = fopen("http://standards.ieee.org/develop/regauth/oui/oui.txt","r");
  $out = fopen("somefile.txt","w");

  while($rec = fgets($fp)){
      // check to see if the line contains '(hex)'
      if (strpos($rec, '(hex)') !== false){
          // if so write it out
          fputs($out, $rec."\n");              
      }
  }
  fclose($fp); 
  fclose($out);

答案 1 :(得分:1)

试试这个

<?php
        $i          = 1;
        $a_line     = "";
        $first_line = "";
        $handle     = @fopen("/tmp/inputfile.txt", "r");

        if ($handle) {
            while (($buffer = fgets($handle, 4096)) !== false) {

                if($i == 1)
                    // here you have first line
                    $first_line = $buffer;
                else {

                    // check the $buffer contains the substring (hex) and XEROX CORPORATION
                    // if it contains put it in another variable

                    $a_line .= $buffer;

                }



            }
            if (!feof($handle)) {
                echo "Error: unexpected fgets() fail\n";
            }
            fclose($handle);
        }
        // finally write the $first_line to a header file
        // then write $a_line to another file

    ?>

答案 2 :(得分:0)

<?php   
error_reporting(0);
$fs=fopen("1.txt", "r");
$ft=fopen("2.txt", "w");

if ($fs==NULL)
{
    echo "Can't Open Source File ...";
    exit(0);
}
if ($ft==NULL)
{
    echo "Can't Open Destination File ...";
    fclose ($fs);
    exit(1);
}

else
{
    while ($ch=fgets($fs))
        fputs($ft, $ch);

    fclose ($fs);
    fclose ($ft);
}

&GT;