views:

382

answers:

2

Currently, I'm grabbing a remote site's XML feed and saving a local copy on my server to be parsed in PHP.

Problem is how do I go about adding some checks in PHP to see if the feed.xml file is valid and if so use feed.xml.

And if invalid with errors (of which sometimes the remote XML feed somes display blank feed.xml), serve a backup valid copy of the feed.xml from previous grab/save ?

code grabbing feed.xml

<?php
/**
* Initialize the cURL session
*/
$ch = curl_init();
/**
* Set the URL of the page or file to download.
*/
curl_setopt($ch, CURLOPT_URL,
'http://domain.com/feed.xml');
/**
* Create a new file
*/
$fp = fopen('feed.xml', 'w');
/**
* Ask cURL to write the contents to a file
*/
curl_setopt($ch, CURLOPT_FILE, $fp);
/**
* Execute the cURL session
*/
curl_exec ($ch);
/**
* Close cURL session and file
*/
curl_close ($ch);
fclose($fp);
?>

so far only have this to load it

$xml = @simplexml_load_file('feed.xml') or die("feed not loading");

thanks

+2  A: 

If it's not pricipial that curl should write directly into file, then you could check XML before re-writing your local feed.xml:

<?php
/**
* Initialize the cURL session
*/
$ch = curl_init();
/**
* Set the URL of the page or file to download.
*/
curl_setopt($ch, CURLOPT_URL, 'http://domain.com/feed.xml');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$xml = curl_exec ($ch);
curl_close ($ch);
if (@simplexml_load_string($xml)) {
    /**
    * Create a new file
    */
    $fp = fopen('feed.xml', 'w');
    fwrite($fp, $xml);
    fclose($fp);
}

?>
Qwerty
totally slipped my mind to do that! thanks :)
p4guru
Hi revisiting this code again and it seems I'm not able to pull the remote xml to save locally whereas the code i posted above in first post works but the save xml file is cut abruptly short ?any ideas ?
p4guru
+2  A: 

How about this? No need to use curl if you just need to retrieve a document.

$feed = simplexml_load_file('http://domain.com/feed.xml');

if ($feed)
{
    // $feed is valid, save it
    $feed->asXML('feed.xml');
}
elseif (file_exists('feed.xml'))
{
    // $feed is not valid, grab the last backup
    $feed = simplexml_load_file('feed.xml');
}
else
{
    die('No available feed');
}
Josh Davis
thanks Josh definitely learning.. glad i signed on on this site :)
p4guru