note 97077 modified in function.simplexml-load-file by danbrown
| From: | danbrown@php.net | Date: | Wed, 31 Mar 2010 16:25:56 +0000 |
| Subject: | note 97077 modified in function.simplexml-load-file by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-167582@lists.php.net to get a copy of this message | ||
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;
}
?>
--was--
A wrapper around simplexml_load_file to circumvent nasty error messages when the xml server times
out or gives a 500 error etc.
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;
}
http://php.net/manual/en/function.simplexml-load-file.php