我现在有一个Wordpress网站,里面有大约30万个页面,还有一台内存为1 1GB的服务器。不幸的是,所有的网站地图生成插件都不能再处理它了。我尝试了3种不同的方法(XMLWriter、SimpleXMLElement和DOMDocument),它们最终都限制在30k左右的页面(xml节点)。
你觉得我该怎么做才能让这件事成功?最坏的情况是,我考虑设置多个cron作业,每天运行一次,每10分钟运行一次,并不断打开/添加到文件中,然后以块的形式添加到文件中,但这显然不是一个最佳的解决方案。我发现了一些片段,声称能够在我的循环中清除内存,但它也没有起到作用。下面是该代码片段的一个示例:
$xml = '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">';
for ($i = 0 ; $i< 20; $i++) {
$query = mysql_query(sprintf("SELECT ID, post_date FROM wp_posts WHERE post_status='publish' LIMIT %s,%s", $i*10000, 10000));
while ($row = mysql_fetch_array($query)) {
$xml .= '<url>';
$xml .= '<loc>'.get_permalink($row['ID']).'</loc>';
$xml .= '<lastmod>'.$row['post_date'].'</lastmod>';
$xml .= '<changefreq>weekly</changefreq>';
$xml .= '<priority>0.6</priority>';
$xml .= '</url>';
}
}
$xml .= '</urlset>';
$sxe = new SimpleXMLElement($xml);
$sxe->asXML("sitemap.xml");发布于 2012-11-24 05:53:14
你为什么一下子把所有的记录都抢过来了?
尝试获取每个请求10000行。并在每次迭代后清理内存。
如果你在cli模式下运行,旧版本的php不会释放内存,所以你可以尝试fork http://php.net/manual/en/function.pcntl-fork.php。
具体操作方法:
sprintf就可以了。LIMIT ($i*10000) 10000代码示例:
for ($i = 0 ; $i< 5 $i++) {
...
$sth = $dbh->prepare('SELECT * FROM table_name LIMIT ? ?');
$sth->execute(array($i*10000, 10000));
...
}另一个代码示例:
<?php
$fileHandle = fopen("sitemap.xml", "w");
fwrite($fileHandle,
'<?xml version="1.0" encoding="UTF-8"?>' .
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"' .
' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' .
' xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9' .
' http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">'
);
for ($i = 0 ; $i< 20; $i++) {
$query = mysql_query(sprintf("SELECT ID, post_date FROM wp_posts WHERE post_status='publish' LIMIT %s,%s", $i*10000, 10000));
$xml = '';
while ($row = mysql_fetch_array($query)) {
$xml .= '<url>'.
'<loc>'.get_permalink($row['ID']).'</loc>' .
'<lastmod>'.$row['post_date'].'</lastmod>' .
'<changefreq>weekly</changefreq>' .
'<priority>0.6</priority>' .
'</url>';
}
fwrite($fileHandle, $xml);
}
fwrite($fileHandle, '</urlset>');
fclose($fileHandle);
echo PHP_EOL . 'memory used: '. memory_get_peak_usage() . PHP_EOL;https://stackoverflow.com/questions/13536032
复制相似问题