6

I need to check the return value of a website output. In case of valid login details it returns a XML file and in case of invalid login details it just returns a string saying "You entered a invalid id".

My problem is I have used this code to check,

$ch = curl_init();

            curl_setopt($ch, CURLOPT_URL, $url);

            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

            $output = curl_exec($ch);

            curl_close($ch);

            if(simplexml_load_string($output)){
                echo 'Is XML';
             }else{
               echo 'Not XML';
                 }

The problem is it is checking and displaying the message, but I am getting these errors

Warning: simplexml_load_string() [function.simplexml-load-string]: Entity: line 1: parser error : Start tag expected, '<' not found in

Warning: simplexml_load_string() [function.simplexml-load-string]:

Warning: simplexml_load_string() [function.simplexml-load-string]: ^ in

Is there a way to sort out these errors. I have been searching in the internet for the past hour without any success.

Thanks

hakre
  • 193,403
  • 52
  • 435
  • 836
Maks
  • 135
  • 1
  • 1
  • 6

3 Answers3

16

Check if the first 5 characters equal <?xml, that should be a pretty good clue.

if(substr($output, 0, 5) == "<?xml") {
    echo 'Is XML';
} else {
    echo 'Not XML';
}
Oldskool
  • 34,211
  • 7
  • 53
  • 66
  • 1
    I think this one would be better `strpos($output, ' – Yekver Dec 28 '13 at 20:25
  • 1
    @Yekver technically substr would be faster, since it doesn't have to search the whole string. The difference is probably negligible though. – Mahn Sep 15 '14 at 12:08
  • Simple and quite elegant when you receive files that are in fact xml even whitout an .xml extension ... – Jiedara Jul 07 '17 at 15:13
  • 2
    A little late, but: This solution will not treat valid XML 1.0 files without the XML declaration as what they are. The XML declaration is recommended but not mandatory. See the first paragraph of that answer over there: https://stackoverflow.com/a/7007781/1704604 – rostbot Nov 16 '18 at 08:54
  • 1
    In particular this won't work with XMP files, which are XML files beginning with ` – hippietrail Nov 12 '19 at 16:06
9
$result = simplexml_load_string ($data, 'SimpleXmlElement', LIBXML_NOERROR+LIBXML_ERR_FATAL+LIBXML_ERR_NONE);
if (false == $result) echo 'error';
akond
  • 15,865
  • 4
  • 35
  • 55
  • But if `if (false == $result)` is really false, I'm getting an error `Node no longer exists`. How can I prevent it? – Daria Dec 10 '15 at 08:07
1

Could also be because the first line of the return data is blank - try $output = trim($output) before you parse the string as XML.

lshepstone
  • 136
  • 9