如何在返回格式错误/意外回复时重试获取xml?

时间:2013-01-10 06:32:06

标签: php curl xml-parsing

您能否告诉我如何改进此功能,以便在服务器返回不在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;
    }
}

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

对于XML解析,我使用simplexml_load_string()函数,如果XML有错误,则返回false。

$sxml = simplexml_load_string($xml_data);

if($sxml === false)
{
    return null;
}
else
{
    return $sxml;
}