我正在尝试将很多单词作为单个条目放入数据库中。
该文件是一个逗号分隔单词的17MB文本文件。
PHP是:
$file = file_get_contents(plugins_url( '/cipher.txt' , __FILE__ ));
$words = explode(',', $file);
foreach($words as $word){
$wpdb->query("INSERT IGNORE INTO cipher_words (word) VALUES ('"" . $word . "'")");
}
我一直遇到类似于以下内容的内存错误:
[20-Feb-2016 15:26:26 UTC] PHP Fatal error: Out of memory (allocated 247726080) (tried to allocate 16777216 bytes) in C:'xampp'htdocs'testsite'wp-content'plugins'joshscipher'cipher.php on line 26
[20-Feb-2016 15:26:29 UTC] PHP Fatal error: Out of memory (allocated 139460608) (tried to allocate 8388608 bytes) in C:'xampp'htdocs'testsite'wp-content'plugins'joshscipher'cipher.php on line 26
[20-Feb-2016 15:26:29 UTC] PHP Fatal error: Out of memory (allocated 247726080) (tried to allocate 16777216 bytes) in C:'xampp'htdocs'testsite'wp-content'plugins'joshscipher'cipher.php on line 26
有没有更好的方法来处理这么大的数组?可能是异步的?
CSV 会更好工作,还是只是满足相同的限制?
我尝试增加PHP限制和WP限制无济于事。
编辑:标记为重复的问题不会收到内存错误。或者任何错误。
如果你想
尝试一下,这里有一个快速的python脚本,它通常比PHP更好地处理大量数据。
import string
import mysql.connector
# Database connection
cnx = mysql.connector.connect(user='admin', password='password', database='python')
cursor = cnx.cursor()
# Get the file contents
with open('cipher.txt', 'r') as content_file:
content = content_file.read()
# 'Explode' the string
content_array = string.split(content, ',')
# Foreach item, insert into db
for x in content_array:
query = "INSERT IGNORE INTO cipher_words (word) VALUES ('"+x+"');"
cursor.execute(query)
# Make sure data is committed to the database
cnx.commit()
# Close database connections
cursor.close()
cnx.close()
您是否愿意仅出于导入而增加 PHP 内存限制?
您可以尝试将其放在 php 文件的顶部。
ini_set('memory_limit', '128M');
或者你可以在 php.ini 中全局更改它。(''xampp''php''php.ini)
memory_limit = 128M
更改全局内存限制后,您可能需要重新启动 apache。