How to avoid out of memory errors when programmatically creating a large number of nodes in drupal?

I create about 150 nodes programmatically and run out of memory errors when doing all of this in one request. (I have a menu callback that generates nodes and calls node_save () on them.)

Example:

for($i=0; $i<150; $i++) {
    $node = new stdClass(); 
    $node->title="Foo $i";
    $node->field_myfield[0]['value'] = "Bar $i";
    ...
    node_save($node);
}

      

I've heard about BatchAPI but never used it. Is this the right tool to get around this? The docs talk about timeouts, but not about memory problems. Is there something simpler that I can lose?

+2


a source to share


2 answers


Yes, batch API can solve this problem. It breaks down your memory usage into separate HTTP requests, each of which has access to your maximum memory limit.



+2


a source


Have you ever used Bulk label operations? ( http://drupal.org/project/views_bulk_operations ) it comes with a view enabled displayed in admin / content / node2 you can edit this to include the Run PHP Code action and also enable the Batch API. this is the easiest way to programmatically modify nodes.

however, since you are creating nodes, you should simply disable $ node at the end of the statement, and this should reduce memory consumption. try:




  for($i=0; $i 150; $i++) {
    $node = new stdClass(); 
    $node->title="Foo $i";
    $node->field_myfield[0]['value'] = "Bar $i";
    ...
    node_save($node);
    unset($node);
  }
}




0


a source







All Articles