seanmt Posted August 24, 2010 Share Posted August 24, 2010 I'm reading data from a database and writing it to an XML file. I then read the content of that file and parse the XML data. It is a little cache script so it only writes data every 180 seconds, whenever it writes data the filesize that is retrieved is still the old file size before the new data was written. This leads to an XML error... The XML error I get: XML error: no element found at line 39 $fp = fopen($file,"r") while (($data = fread($fp, filesize($file)))) { xml_parse($xml_parser, $data, feof($fp)); } fclose($fp); Quote Link to comment Share on other sites More sharing options...
AbraCadaver Posted August 24, 2010 Share Posted August 24, 2010 I'm not sure an I haven't looked into it. I would assume that since in the same script you have already accessed the file that PHP has cached the stat call results, not sure. But why not use file_get_contents() to just read in the whole file? Quote Link to comment Share on other sites More sharing options...
Psycho Posted August 24, 2010 Share Posted August 24, 2010 There is another solution. As I understand it, when the page loads it is making a determination of whether or not the data is 180 seconds old. If not, it reads the current XML file. But, if the file is older than 180 seconds it queries the db and writes a new file - then you attempt to read that new file (which is where you are experiencing the error.) If you just queried the database and wrote the new file - why do you need to read the file? You already have the content. By trying to read the file (of data you just wrote) the script is being inefficient. Here is a "rough" example of a possible solution. This is not tested, and I don't know if this would work as is - but the logic is valid if((time()-filemtime($data)) < 180) { //Read the current file xml_parse($xml_parser, $data, feof($fp)); } else { //Get new data $query = "SELECT * FROM table WHERE foo='bar'"; $result = mysql+query($query); //Create loop to generate XML content into variable while($record = mysql_fetch_assoc($result)) { $xml_data = //Process to create new XML content } //Write the data to xml file $fh = fopen($data, 'w') or die("can't open file"); fwrite($fh, $xml_data); //Parse the xml variable - not the xml file just created xml_parse($xml_parser, $xml_data); } Quote Link to comment Share on other sites More sharing options...
seanmt Posted August 27, 2010 Author Share Posted August 27, 2010 Ah yes it makes sense to just output the data seeing as I am accessing the database anyway and writing it to a file. All sorted now thanks guys. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.