tags:

views:

250

answers:

2

I am reading an XML feed and would like to compare to an old version to check for updates. My problems at the moment are that I can't seem to make a copy of a SimpleXML object and the other problem is I'm not sure I can directly compare them. This is my code as it stands, feel free to shoot me down if it's rubbish. I'm obviously just testing on local files, but I intend to eventually load from the web. Is it okay to use sleep for very long periods? I was thinking 15 minute interval is often enough for my purpose.

error_reporting(E_NOTICE);
$file = 'tmbdata_sm.xml';

$xml_old = "";
while(true){
 $xml = simplexml_load_file($file);

 if($xml != $xml_old){
 foreach($xml->channel->item as $item){
  echo $item->title . "\n";
  echo $item->link . "\n";
 }
 $xml_old = clone $xml;
 $xml = "";
 }else{
 echo 'no change';
 }

sleep(60);
}
A: 

I think you can't compare simple xml objects in this way.

I would try to download the xml using whatever you feel comfortable with (say, cURL extension http://php.net/manual/en/book.curl.php), then compare the xml text strings, and then when you find they are differen, use simplexml_load_string() to parse the xml text.

hth

Roland Bouman
Or even just use `file_get_contents()` on the URL, as that's the equivalent to `simplexml_load_file()`. Otherwise, I was about to give the same answer: just compare them as strings.
Josh Davis
+1  A: 

Without a definition of what "updated" means in your context I'm afraid your question may remain unanswered. String compare might work, but a better and faster way would be to use filemtime() which lets you know the last time that the file was modified.

Also you should refrain from using sleep() in an infinite loop like you are doing. I don't think having PHP running indefinitely will be healthy for your computer or your server. The proper way to do this is either a cronjob when using UNIX, or the task scheduler when in Windows.

tedeh
filemtime() would be an elegant solution but as I want to read the xml from http I don't think it will work (although I will try it).Can you provide an explanation, or link, as to why using sleep in an infinite loop is a bad thing? I'm not disagreeing with you, I'd just like to know and couldn't find any info (and I mean running php from the cmd line, obviously an infinite loop for a script on the web is not a good thing). My host (nfs) currently doesn't allow cron jobs and I can see on my local machine that php uses neither cpu nor ram using sleep(5*60)
aland