possien Posted May 7, 2011 Share Posted May 7, 2011 I have a script that uses simplexml_load_file to download weather xml files. It works great except when the file doesn't exist. The server returns an HTML page when the xml file isn't available but the title is something.xml. How can I check to be sure it is an xml file and handle the error when it isn't. I have tried file_exists and access the return code (it's always 200). Can I access the doctype and determine if it HTML or XML? Quote Link to comment https://forums.phpfreaks.com/topic/235743-help-with-simplexml_load_file-when-file-doesnt-exist/ Share on other sites More sharing options...
fugix Posted May 7, 2011 Share Posted May 7, 2011 if you want to check and see what file type is being downloaded...you can use this $ext = substr($fileName, strrpos($fileName, '.') + 1); what this will return is any text after the period...so if i had a file name "test.txt", the code will return "txt". You can then check to see if it returns xml...if it does, act accordingly, if not, set up code for that as well Quote Link to comment https://forums.phpfreaks.com/topic/235743-help-with-simplexml_load_file-when-file-doesnt-exist/#findComment-1211768 Share on other sites More sharing options...
jonsjava Posted May 7, 2011 Share Posted May 7, 2011 I see your problem. Fugix, His issue isn't with if he can be sure it is an XML file. He is grabbing a file remotely, and sometimes, the remote server gives an error. The simplest method I can come up with is to check the input for "<?xml". If that isn't there, error out with custom error handling. Pseudo code to follow <?php $xml_url = "http://some_site/file.xml"; $xml = file_get_contents($xml_url); if (!stristr($xml,"?xml"){ //error } else{ //good to go } Quote Link to comment https://forums.phpfreaks.com/topic/235743-help-with-simplexml_load_file-when-file-doesnt-exist/#findComment-1211772 Share on other sites More sharing options...
possien Posted May 7, 2011 Author Share Posted May 7, 2011 jonsjava code worked great, thanks! The erroneous files started with !DOCTYPE HTML and the test for ?xml works. Quote Link to comment https://forums.phpfreaks.com/topic/235743-help-with-simplexml_load_file-when-file-doesnt-exist/#findComment-1211786 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.