how to avoid 'out of memory' errors when programmatically generating a lot of nodes in drupal?

旧城冷巷雨未停 提交于 2019-12-24 02:14:31

问题


I'm creating about 150 nodes programmatically and running into 'out of memory' errors when doing it all in a single request. (I have a menu callback that generates the 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 of BatchAPI, but never used it. Is that the right tool to get around this? The docs talk about timeouts, but not memory issues. Is there something simpler that I might be missing?


回答1:


Yes, Batch API can solve this problem. It will break up your memory usage into separate HTTP requests, each with access to your full memory limit.




回答2:


have you ever used Views Bulk Operations? (http://drupal.org/project/views_bulk_operations) it comes with a bundled view displayed at admin/content/node2 you may edit that to enable a "Run PHP code" action, as well as turn on Batch API. it is the easiest way to programmaticaly modify nodes.

however, since you are creating the nodes, you should just unset the $node at the end of the instruction, and it should tone down your memory usage. 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);
  }
}



来源:https://stackoverflow.com/questions/2725448/how-to-avoid-out-of-memory-errors-when-programmatically-generating-a-lot-of-no

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!