title: Parsing and Writing Files in PHP
body: <p>I'm attempting to open a directory full of text files, and then read each file line-by-line, writing the information in each line to a new file.  Within each text file in the directory I'm trying to iterate, the information is formed like:</p>
  
  <pre class="lang-none prettyprint-override"><code>JunkInfo/UserName_ID_Date_Location.Type
  </code></pre>
  
  <p>So I want to open every one of those text files and write a line to my new file in the form of:</p>
  
  <pre class="lang-none prettyprint-override"><code>UserName,ID,Date,Location,Type
  </code></pre>
  
  <p>Here's the code I've come up with so far:</p>
  
  <pre><code>&lt;?php
  
  $my_file = 'info.txt';
  $writeFile = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file); //implicitly creates file
  
  $files = scandir('/../DirectoryToScan');
  foreach($files as $file)
  {
      $handle = @fopen($file, "r");
      if ($handle) 
      {
          while (($buffer = fgets($handle, 4096)) !== false) 
          {
              $data = explode("_", $buffer);
              $username = explode("/", $data[0])[1];
              $location = explode(".", $data[3])[0];
              $type = explode(".", $data[3])[1];
  
              $stringToWrite = $username . "," . $data[1] . "," . $data[2] . "," . $location . "," . $type;
  
              fwrite($writeFile, $stringToWrite);
          }
  
          if (!feof($handle)) 
          {
               echo "Error: unexpected fgets() fail\n";
          }
          fclose($handle);
      }
  }
  
  fclose($writeFile);
  ?&gt;
  </code></pre>
  
  <p>So my problem is, this doesn't seem to work. I just never get anything happening -- the output file is never written and I'm not sure why.</p>