【发布时间】:2015-05-15 10:00:54
【问题描述】:
我目前在连接到 api 服务的网站主页上有一个脚本。有时 api 响应时间过长,如果响应时间超过三秒,我试图找出一种显示默认结果的方法。我不知道该怎么做。这是我的 curl 脚本:
class Ofertas{
public $Name;
public $HotelId;
public $Coordinates = array();
public $Longs;
public $Response = array();
public function __construct($var){
$ofertas = new SqlIt('SELECT destination_id, destination_name, bottom_link, link FROM **** ORDER BY slot ASC LIMIT '.$var,'select',array());
foreach($ofertas->Response as $did){
$coor = new SqlIt("SELECT CenterLatitude, CenterLongitude, RegionName FROM ***** WHERE RegionID = ? LIMIT ".$var,"select",array($did->destination_id));
array_push($this->Coordinates,array($coor->Response[0]->CenterLatitude,$coor->Response[0]->CenterLongitude,$coor->Response[0]->RegionName));
}
$i = 0;
$url = "http://apiurl";
$curl_arr = array();
$master = curl_multi_init();
$i = 0;
foreach($this->Coordinates as $co){
$xml = '<xmlrequesthere>xml code goes here for request</xmlrequesthere>';
$curl_arr[$i] = curl_init($url);
curl_setopt($curl_arr[$i], CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_arr[$i], CURLOPT_POSTFIELDS, $xml);
curl_setopt($curl_arr[$i], CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_arr[$i], CURLOPT_HTTPHEADER, array('Accept: application/xml'));
curl_setopt($curl_arr[$i], CURLOPT_HEADER, 0);
curl_setopt($curl_arr[$i], CURLOPT_CONNECTTIMEOUT ,1); // number of seconds to wait for initial connection
curl_setopt(curl_arr[$i], CURLOPT_TIMEOUT, 2); //timeout for entire process.
curl_multi_add_handle($master, $curl_arr[$i]);
do {
curl_multi_exec($master,$running);
} while($running > 0);
if (curl_errno($curl_arr[$i])) {
//fetch default hotels from the database
}else{
$results = curl_multi_getcontent ( $curl_arr[$i] );
$apit = simplexml_load_string($results);
$j['destination'] = $ofertas->Response[$i]->destination_name;
$j['button'] = $ofertas->Response[$i]->bottom_link;
$j['link'] = $ofertas->Response[$i]->link;
$j['hotels'] = array();
foreach($apit->HotelList->HotelSummary as $res){
$hh['name'] = $res->name.'';
$hh['hid'] = $res->hotelId.'';
$hh['city'] = $res->city.'';
$hh['rate'] = $res->lowRate.'';
$hh['thumb'] = $res->thumbNailUrl.'';
array_push($j['hotels'],$hh);
}
}
array_push($this->Response, $j);
$i++; }
}
}//end of class
我应该在某处关闭连接吗?或者我只是想像我说的那样添加一个超时。任何帮助将不胜感激!谢谢!
【问题讨论】: