简体   繁体   English

加载外部XML并使用PHP保存

[英]Load external XML and save it using PHP

I want to load and save an external XML file that changes continuously eg "http://something.com/file.xml" 我想加载并保存一个不断变化的外部XML文件,例如“ http://something.com/file.xml”

Sometimes the file is not available because server is overloaded or down and I want to use this file instead and re-save it if the next load is available also let people know the file that they are reading is a backup file because the original is not available. 有时该文件不可用,因为服务器过载或关闭,我想改用此文件,如果下次加载可用,请重新保存它,还可以让人们知道他们正在读取的文件是备份文件,因为原始文件不是可用。

I read about simplexml_load_file and DOMDocument and I don't know which one is the better solution. 我读到有关simplexml_load_file和DOMDocument的文章,但我不知道哪个是更好的解决方案。

$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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM