0

我需要加快以下代码的 simple_xml_file 部分。

我在想多线程......有什么想法吗?

我怎样才能加快获取 xml 文件的那部分代码。

<?php


$k = $_GET['key'];


echo "<ul id=\"List\">\n";
foreach ($feed as $url2):
$title=$url2['name'];
$url=$url2['url'];

if (strpos($url, $key)==true) {
//Load XML
$temp = simplexml_load_file("http://api.site.com/web?uri=$url"); //Need to speed this
//Echo
echo "<li>".$temp->filter->filterResponse->filteredText."</li>";
}else{
//URL Contains Nothing Check Title
if(strpos($title,$key)==true)
{

$temp = simplexml_load_file("http://api.site.com/web?uri=$url"); //Need to speed this
//Echo
echo "<li>".$temp->filter->filterResponse->filteredText."</li>";
}
}

endforeach;
echo "</ul>";

?>
4

2 回答 2

1

PHP 不支持多线程,因此您无能为力。
顺便提一句。我认为加入这两个条件要干净得多,因为无论如何您都执行相同的操作:

if (strpos($url, $key) == true OR strpos($title,$key) == true) {
   //Load XML
   $temp = simplexml_load_file("http://api.site.com/web?uri=$url"); //Need to speed this
   //Echo
   echo "<li>".$temp->filter->filterResponse->filteredText."</li>";
}
于 2013-07-08T13:22:01.287 回答
1

您可以使 API 服务器的 http 请求与 curl 并行运行,如下所示:

//create the multiple cURL handle
$mh = curl_multi_init();
// gather curl handlers into an array for later use and add them to the multi request
$requests = array();
foreach ($feed as $url2) {
    $url=$url2['url'];
    $title=$url2['name'];

    // strpos can return 0 which will evaluate to false even if the needle is in fact in the beginning of the haystack
    if (strpos($url, $key) !== false || strpos($title,$key) !== false) {
        $ch = curl_init("http://api.site.com/web?uri=".$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_multi_add_handle($mh, $ch);
        $requests[] = $ch;
    }
}

// execute the requests
$running=null;
do {
    // exec the multy request, update the $running variable
    while (CURLM_CALL_MULTI_PERFORM === curl_multi_exec($mh, $running));
    // break the loop if we are done
    if (!$running) { 
        break;
    }
    // block until something interesting happens on a request
    while (($res = curl_multi_select($mh)) === 0);
    // if its an error, do something about it!
    if ($res === false) {
        // handle select errors here!
        break;
    }
    // repeat forever (or until we break out)
} while (true);

// loop trough the results
foreach ($requests as $ch) {
    // load resposne
    $xml = simplexml_load_string(curl_multi_getcontent($ch));

    // do your original processing
    echo "<li>".$xml->filter->filterResponse->filteredText."</li>";

    // clean up curl handler
    curl_multi_remove_handle($mh, $ch);
}
curl_multi_close($mh); 

如果没有真实数据(除了语法),我无法真正测试它,但你明白了。你的用法strpos()对我来说看起来很奇怪,0如果针在干草堆的开头但0 == true评估为假,它可能会 reutnr (零号),我不确定这是否是你想要的。

于 2013-07-08T14:39:03.763 回答