2

I would like to stop a simplexml_load_file if it takes too long to load and/or isn't reachable (occasionally the site with the xml goes down) seeing as I don't want my site to completely lag if theirs aren't up.

I tried to experiment a bit myself, but haven't managed to make anything work.

Thank you so much in advance for any help!

2 Answers2

2

You can't have an arbitrary function quit after a specified time. What you can do instead is to try to load the contents of the URL first - and if it succeeds, continue processing the rest of the script.

There are several ways to achieve this. The easiest is to use file_get_contents() with a stream context set:

$context = stream_context_create(array('http' => array('timeout' => 5)));

$xmlStr = file_get_contents($url, FALSE, $context);
$xmlObj = simplexml_load_string($xmlStr);

Or you could use a stream context with simplexml_load_file() via the libxml_set_streams_context() function:

$context = stream_context_create(array('http' => array('timeout' => 5)));

libxml_set_streams_context($context);
$xmlObj = simplexml_load_file($url);

You could wrap it as a nice little function:

function simplexml_load_file_from_url($url, $timeout = 5)
{
    $context = stream_context_create(
        array('http' => array('timeout' => (int) $timeout))
    );
    $data = file_get_contents($url, FALSE, $context);

    if(!$data) {
        trigger_error("Couldn't get data from: '$url'", E_USER_NOTICE);
        return FALSE;
    }

    return simplexml_load_string($data);
} 

Alternatively, you can consider using the cURL (available by default). The benefit of using cURL is that you get really fine grained control over the request and how to handle the response.

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
1

You should be using a stream context with a timeout option coupled with file_get_contents

$context = stream_context_create(array('http' => array('timeout' => 5))); //<---- Setting timeout to 5 seconds...

and now map that to your file_get_contents

$xml_load = file_get_contents('http://yoururl', FALSE, $context);
$xml = simplexml_load_string($xml_load);
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126