php等到上一个函数完成

时间:2011-05-02 11:35:39

标签: php function memory memory-management

我正在尝试创建一些xml,主要是通过阅读rss feed并添加一些自定义标记。我已经创建了一个包含我的代码的函数,现在我想用不同的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,即使我取消了所有函数中创建的变量和对象。如果我将函数调用减少到1或2,一切正常 它有什么办法可以运作吗?我在考虑每个函数调用在开始之前等待前一个完成,但是怎么能这样做呢?

希望有人可以提供帮助。 提前谢谢。

2 个答案:

答案 0 :(得分:1)

你想要的东西是php中的正常行为。它是从上到下完成的。每个函数都必须等待,直到上一个函数完成。我认为你的问题是php.ini中的内存限制。打开文件并搜索指令:memory_limit http://www.php.net/manual/en/ini.core.php#ini.memory-limit增加它以满足您的需求。

答案 1 :(得分:1)

你要取消$ doc而不是$ newDoc,尝试添加

unset($newDoc);

在该功能结束时。

正如其他人所说,问题在于你是在泄漏记忆还是超出你的记忆限制;这与等到上一个代码完成无关。

或者,您可以将每次调用load_custom_rss()放入单独的请求中,因此脚本会调用一个然后重新加载,即

$i = $_GET['i'];

if ($i==0)
    load_custom_rss('http://www.somesite.com/rssfeed/articles', 'articles.xml'); 
elseif ($i==1)
    load_custom_rss('http://www.somesite.com/rssfeed/jobs', 'jobs.xml');

... etc ...

else
    die("I'm done");

header("Location: myself.php?i=".($i+1));

您重新加载脚本的方法当然可能会有所不同,具体取决于页面是否需要首先呈现任何HTML。