test for complete xml

is there a way to test that XML is complete. I have a function that is in a loop waiting for an xml file to appear. when the file appears it is loaded with the simplexml_load_file() function. the problem is that this little loop that i have reads the file and tries to load it while its still being written by another program. This results in incomplete XML code. is there a way to test it. I get all these error messages on the screen.You're relying on polling the filesystem?

I have several suggestions:

1. Don't poll the filesystem, find some more reasonable way to do things
2. Check the modification time of the file, and wait until it reaches a certain age (say 30 seconds) before reading it
3. Use an XML parser which checks for well-formedness (I know nothing about simplexml, if you use DOM it will throw an exception if the document is not well-formed). When you detect a badly formed document (i.e. catch the exception), wait a while and try again later. If of course it's still badly formed, someone could genuinely have uploaded a badly formed document.
4. Have the application writing the file place a write-lock on the file, and your app reading it place a read-lock on before reading - then it will be blocked until the writing is finished.

MarkBoth DOM and SimpleXML check the XML file is well formed and generate return a null reference or false if the XML is bad. You can check for this before continuing.

<?php

if (! $doc = @simplexml_load_file('/path/to/file')) {
echo('error loading file');
}

echo ($doc->asXML());
?>

Don't forget the error supression operator, otherwise the simplexml_load_file() function will spit out a load of warnings.One straightforward initial check is to see if the last closing tag is the last thing in the document, and matches the first opening tag.
 
Back
Top