Compare XML in PHP without hashing
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. 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);
}
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.
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), then compare the xml text strings, and then when you find they are different, use simplexml_load_string()
to parse the xml text.
精彩评论