I’m in a new project where I need to load XML files from other web services and handle their content.
The external service is also under developtment and therefore it’s kind of laggy to work with.
Right now, I’m using this way:
if (fopen(Constants::XML_AUTH . $this->xmlString, "r") == true) {
$this->xmlDom = simplexml_load_file(
Constants::XML_AUTH . $this->xmlString,
'SimpleXMLElement');
if (!$this->xmlDom) {
$this->setStatus(Constants::XML_NOTLOADED);
}
else {
$this->setStatus($this->xmlDom->status);
$this->setType();
}
}
This works fine as long as the external webservice is running und responding.
But as soon as it lags, the simplexml_load_file() function uses all time the whole script has, trying to load from the source and finally the script returns a beautiful white screen.
So I was wondering if there is a possibility to kind of control the amount of time, the script has to load the external XML and if not successful, print an error.
Or is there even a better approach to safely load an external XML file with PHP?
I’m using symfony 1.4 on this project.
Open the remote file with stream_get_contents, it will return a stream resource which means that it can be read without having to be pre-loaded in memory
Parse the stream with XMLReader, it is able to parse a stream without preloading it fully into memory as well
The best is to sync the remote data in a local database, because it will be faster and also resistant to remote failures … of course this is not possible in many case (who’s going to sync last.fm XML api ? i tried it doesn’t work :))