簡體   English   中英

加載外部XML並使用PHP保存

[英]Load external XML and save it using PHP

我想加載並保存一個不斷變化的外部XML文件,例如“ http://something.com/file.xml”

有時該文件不可用,因為服務器過載或關閉,我想改用此文件,如果下次加載可用,請重新保存它,還可以讓人們知道他們正在讀取的文件是備份文件,因為原始文件不是可用。

我讀到有關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