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?

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.