vegac Posted July 20, 2014 Share Posted July 20, 2014 Hi, I am a newbie to php and am trying to copy mysql data to a text file. The format I need to create is { "data": [ { "name": "Tiger Nixon", "position": "System Architect", "salary": "$320,800", "start_date": "2011/04/25", "office": "Edinburgh", "extn": "5421" }, My code generates the file but does not enter the mysql data. Below is an excerpt from the code relating to the fwrite function. // Insert a new row in the table for each person returned while($row = mysql_fetch_array($qry_result)){ $myFile = "testFile.txt"; $fh = fopen($myFile, 'w') or die("can't open file"); $stringData = "{\n\"data\": [\n"; fwrite($fh, $stringData); $dbstringData[] = implode(",",$row); fwrite($fh, implode("\r\n", $dbstringData)); $stringData = "{\nTracy ,\n},\n"; fwrite($fh, $stringData); $stringData = "]\n}\n"; fwrite($fh, $stringData); fclose($fh); ?> Thanks. Quote Link to comment Share on other sites More sharing options...
Psycho Posted July 21, 2014 Share Posted July 21, 2014 The format you want is JSON. There is no need to build it yourself, PHP has a built in function to convert an array to JSON. Just run the query and convert the result array to JSON. You'll want to create one array for all the records, the write the entire thing to your output file. Be sure to use the fetch_assoc() method. Also, don't repeat things in loops that don't need to be repeated. For example, why would you need to redefine $myFile in every iteration of the loop? Only do the things in loops that need to be repeated $myFile = "testFile.txt"; $data = array() while($row = mysql_fetch_assoc($qry_result)) { $data[] = $row; } //Open file for writing $fh = fopen($myFile, 'w') or die("can't open file"); //Convert data to JSON format and write to file $stringData = json_encode($data); fwrite($fh, $stringData); //close file fclose($fh); 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.