【发布时间】:2011-05-02 11:35:38
【问题描述】:
我正在尝试创建一些 xml ,基本上是通过阅读 rss 提要并向它们添加一些自定义标签。我制作了一个包含我的代码的函数,现在我想用不同的 rss url 多次调用该函数。每次调用都会生成一个不同的 .xml 文件。
我使用 DOMDocument 加载和解析 rss,并使用 simple_html_dom 加载和解析每个 rss 项的链接以从 html 中获取一些内容。
这是我的代码的简化示例:
<?php
include('simple_html_dom.php');
load_custom_rss('http://www.somesite.com/rssfeed/articles', 'articles.xml');
load_custom_rss('http://www.somesite.com/rssfeed/jobs', 'jobs.xml');
load_custom_rss('http://www.somesite.com/rssfeed/press', 'press.xml');
//up to 20 similar function calls here...
function load_custom_rss($link, $filename){
$doc = new DOMDocument();
$doc->load($link);
$newDoc = new DOMDocument('1.0', 'UTF-8');
$rss = $newDoc->createElement('rss');
$channel = $newDoc->createElement('channel');
$newDoc->appendChild($rss);
$rss->appendChild($channel);
foreach ($doc->getElementsByTagName('item') as $node) {
//here is some code to read items from rss xml / write them to new xml document.
//Code missing for simplicity
//Next lines used to get some elements from the html of the item's link
$html = new simple_html_dom();
html->load_file($node->getElementsByTagName('link')->item(0)->nodeValue);
$ret = $html->find('#imgId');
}
$newDoc->formatOutput = true;
$fh = fopen($filename, 'w') or die("can't open file");
fwrite($fh, $newDoc->saveXML());
fclose($fh);
unset($doc);
//unset ALL variables and objects created in this function...
//........
}//function end
?>
我的问题是函数的每次调用都会消耗相当多的内存,因此在函数 apache 的第 3 次或第 4 次调用之后会抛出致命错误,因为脚本消耗的内存量大于 memory_limit,即使我取消设置 ALL在函数中创建的变量和对象。如果我将函数调用减少到 1 或 2 次,一切正常。
有什么办法可以工作吗?我在想每个函数调用都在开始之前等待前一个函数调用完成,但这怎么能做到呢?
希望有人可以提供帮助。 提前致谢。
【问题讨论】:
-
这必须从 apache 运行还是可以从命令行运行?如果是后者,你对时间和内存没有这么严格的限制。
标签: php function memory memory-management