8

I have a PHP-driven site that includes an XML stock feed, which is remotely served from ASP (i.e. the XML feed url is of the order: http://remote.com/client.asp).

As the feed is often unavailable (by which I mean the site returns an ASP error) I'd like to check if the feed is well-formed XML before including it. My usual url_exists function doesn't do the trick as of course the URL does exist even when 'erroring'.

TIA.

da5id
  • 9,100
  • 9
  • 39
  • 53
  • 1
    Note: be careful with terminology. What you're describing sounds like "well-formed" XML, which means something different to "valid" XML. – cletus Jan 13 '09 at 22:24
  • Quite right cletus (thanks) editing now... – da5id Jan 13 '09 at 22:27

1 Answers1

21

Use cURL to get the result and simplexml to check if the XML is well-formed.

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "http://remote.com/client.asp");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
if (simplexml_load_string($output)) {
  // well-formed XML
} else {
  // it isn't
}
cletus
  • 616,129
  • 168
  • 910
  • 942
  • Thanks. I'm already using something very similar to that, and it is this script that often throws an error. Though I'm using simplexml_load_file, would there be a difference with simplexml_load_string? – da5id Jan 13 '09 at 22:25
  • I'm having problem with SimpleXML and it's very weird. Apparently simplexml_load_file() from URL and simplexml_load_string() from cURL result of URL could get different result. One could fail while another could work...It's beyond me how that happened. Taking a look at my cURL function now – fred Mar 28 '12 at 07:05
  • simplexml_load_string throws warnings when going through a html... it is not failing where it should – Alfonso Fernandez-Ocampo Aug 23 '15 at 08:27