1

你能给我一些想法如何改进这个功能,以便它在服务器返回不在 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;
    }
}
4

1 回答 1

1

你可以试试这个。我还没有测试出来。

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;
}
于 2013-01-10T07:30:51.793 回答