Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grab, cache and parse remote XML feed, validation checks in PHP

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

like image 915
p4guru Avatar asked Feb 14 '10 17:02

p4guru


1 Answers

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

?>
like image 172
Qwerty Avatar answered Oct 13 '22 18:10

Qwerty