你能给我一些想法如何改进这个功能,所以它处理意外的回复当服务器返回输出不是在xml,例如一个简单的服务器错误信息在html,然后重试抓取xml?
function fetch_xml($url, $timeout=15)
{
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_HEADER => 0,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_CONNECTTIMEOUT => (int)$timeout,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_URL => $url)
);
$xml_data = curl_exec($ch);
curl_close($ch);
if (!empty($xml_data)) {
return new SimpleXmlElement($xml_data);
}
else {
return null;
}
}
你可以试试。我还没有测试过。
function fetch_xml($url, $timeout = 15, $max_attempts = 5, $attempts = 0)
{
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_HEADER => 0,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_CONNECTTIMEOUT => (int)$timeout,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_URL => $url)
);
$xml_data = curl_exec($ch);
curl_close($ch);
if ($attempts <= $max_attempts && !empty($xml_data)) // don't infinite loop
{
try
{
return new SimpleXmlElement($xml_data);
}
catch (Exception $e)
{
return fetch_xml($url, (int)$timeout, $max_attempts, $attempts++);
}
}
return NULL;
}