Voting

: zero plus three?
(Example: nine)

The Note You're Voting On

jamie at splooshmedia dot co dot uk
15 years ago
A wrapper around simplexml_load_file to circumvent nasty error messages when the xml server times out or gives a 500 error etc.

<?php
function loadXML2($domain, $path, $timeout = 30) {

/*
Usage:

$xml = loadXML2("127.0.0.1", "/path/to/xml/server.php?code=do_something");
if($xml) {
// xml doc loaded
} else {
// failed. show friendly error message.
}
*/

$fp = fsockopen($domain, 80, $errno, $errstr, $timeout);
if(
$fp) {
// make request
$out = "GET $path HTTP/1.1\r\n";
$out .= "Host: $domain\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);

// get response
$resp = "";
while (!
feof($fp)) {
$resp .= fgets($fp, 128);
}
fclose($fp);
// check status is 200
$status_regex = "/HTTP\/1\.\d\s(\d+)/";
if(
preg_match($status_regex, $resp, $matches) && $matches[1] == 200) {
// load xml as object
$parts = explode("\r\n\r\n", $resp);
return
simplexml_load_string($parts[1]);
}
}
return
false;

}
?>

<< Back to user notes page

To Top