0

我想加载并保存一个XML不断变化的外部文件,例如“http://something.com/file.xml”

有时文件不可用,因为服务器超载或停机,我想改用这个文件,如果下一次加载可用则重新保存它也让人们知道他们正在阅读的文件是备份文件,因为原始文件不是可用的。

我阅读了有关 simplexml_load_file 和 DOMDocument 的信息,但我不知道哪个是更好的解决方案。

4

1 回答 1

1
$url = "http://www.test.com/xmlfile.xml";
$timeout = 10;

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);

try {
    $response = curl_exec($curl);
    curl_close($curl);

    // success! Let's parse it and perform whatever action necessary here.
    if ($response !== false) {
        /** @var $xml SimpleXMLElement */
        $xml = simplexml_load_string($response);
        $xml->saveXML("tofile.xml");
    } else {
        // Warn the user here
    }
} catch (Exception $ex) {
    // Let user's know that there was a problem
    curl_close($curl);
}
于 2012-12-11T22:27:09.820 回答