Jump to content

Recommended Posts

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.

Link to comment
https://forums.phpfreaks.com/topic/290026-writing-mysql-to-txt-file/
Share on other sites

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);
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.