title: How do I get multiple results from a file opened only once using proc_open?
body: <p>I have a command run using exec() which returns a value from within a very large data file, but it has to run millions of times. In order to avoid having the file opened each time in a loop, I want to move to a <code>proc_open</code>-based solution, where the file pointer is created once for efficiency, but can't work out how to do this.</p>
  
  <p>Here is the <code>exec</code>-based version, which works but is slow, presumably because it has to open the file in each iteration:</p>
  
  <pre><code>foreach ($locations as $location) {
      $command = "gdallocationinfo -valonly -wgs84 datafile.img {$location['lon']} {$location['lat']}";
      echo exec ($command);
  }
  </code></pre>
  
  <p>My attempt at a <a href="http://php.net/proc_open" rel="nofollow"><code>proc_open</code></a>-based code is as follows:</p>
  
  <pre><code>$descriptorspec = array (
      0 =&gt; array ('pipe', 'r'),  // stdin - pipe that the child will read from
      1 =&gt; array ('pipe', 'w'),  // stdout - pipe that the child will write to
      // 2 =&gt; array ('file', '/tmp/errors.txt', 'a'), // stderr - file to write to
  );
  
  $command = "gdallocationinfo -valonly -wgs84 datafile.img";
  $fp = proc_open ($command, $descriptorspec, $pipes);
  
  foreach ($locations as $location) {
      fwrite ($pipes[0], "{$location['lon']} {$location['lat']}\n");
      fclose ($pipes[0]);
      echo stream_get_contents ($pipes[1]);
      fclose ($pipes[1]);
  }
  
  proc_close ($fp);
  </code></pre>
  
  <p>This correctly gets the first value, but then generates an error for each subsequent iteration:</p>
  
  <pre><code>3.3904595375061 
  
  Warning: fwrite(): 6 is not a valid stream resource in file.php on line 11
  Warning: fclose(): 6 is not a valid stream resource in file.php on line 12
  Warning: stream_get_contents(): 7 is not a valid stream resource in file.php on line 13
  Warning: fclose(): 7 is not a valid stream resource in file.php on line 14
  
  Warning: fwrite(): 6 is not a valid stream resource in file.php on line 11
  ...
  </code></pre>