title: How to "release" memory in loop?
body: <p>I have a script that is running on a shared hosting environment where I can't change the available amount of PHP memory. The script is consuming a web service via soap. I can't get all my data at once or else it runs out of memory so I have had some success with caching the data locally in a mysql database so that subsequent queries are faster. </p>
  
  <p>Basically instead of querying the web service for 5 months of data I am querying it 1 month at a time and storing that in the mysql table and retrieving the next month etc. This usually works but I sometimes still run out of memory.</p>
  
  <p>my basic code logic is like this:</p>
  
  <ol>
  <li>connect to web service using soap;</li>
  <li>connect to mysql database</li>
  <li>query web service and store result in variable $results;</li>
  <li>dump $results into mysql table</li>
  <li>repeat steps 3 and 4 for each month of data</li>
  </ol>
  
  <p>the same variables are used in each iteration so I would assume that each batch of results from the web service would overwrite the previous in memory? I tried using unset($results) in between iterations but that didn't do anything. I am outputting the memory used with memory_get_usage(true) each time and with every iteration the memory used is increased. </p>
  
  <p>Any ideas how I can fix this memory leak? If I wasn't clear enough leave a comment and I can provide more details. Thanks!</p>
  
  <p>***EDIT</p>
  
  <p>Here is some code (I am using nusoap not the php5 native soap client if that makes a difference):</p>
  
  <pre><code>$startingDate = strtotime("3/1/2011");
  $endingDate = strtotime("7/31/2011");
  // connect to database
  mysql_connect("dbhost.com", "dbusername" "dbpassword");
  mysql_select_db("dbname");
  // configure nusoap
  $serverpath ='http://path.to/wsdl';
  $client = new nusoap_client($serverpath);
  // cache soap results locally
  while($startingDate&lt;=$endingDate) {
      $sql = "SELECT * FROM table WHERE date &gt;= ".date('Y-m-d', $startingDate)." AND date &lt;= ".date('Y-m-d', strtotime($startingDate.' +1 month'));
      $soapResult = $client-&gt;call('SelectData', $sql);
      foreach($soapResult['SelectDateResult']['Result']['Row'] as $row) {
          foreach($row as &amp;$data) {
              $data = mysql_real_escape_string($data);
          }
          $sql = "INSERT INTO table VALUES('".$row['dataOne']."', '".$row['dataTwo']."', '".$row['dataThree'].")";
          $mysqlResults = mysql_query($sql);
      }
      $startingDate = strtotime($startingDate." +1 month");
      echo memory_get_usage(true); // MEMORY INCREASES EACH ITERATION
  }
  </code></pre>