Jump to content

Help with simplexml_load_file when file doesn't exist


possien

Recommended Posts

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?

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

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
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.