MySQL to tab formatted TXT(datafeed) converter script-PHP

MySQL to Google Based Datafeed Converter PHP Script

Hello Friends !!

Currently I am working on one project in which I have to store data in Google Merchant Center.

This is a Google Product Search which is used for search any product around the world. Currently many shopping sites stores their products in Google Product Search.

For store data in google product search, Google supports txt file with tab seperated.

After some reserch I have made one PHP script which store data from MySQL table to txt file with tab seperated.

Here is the code for this :

if (!$_POST[‘submit’]){
}else{$table = $_POST[‘mytable’];

if (!eregi(“[a-z0-9_]{1,64}”,$table)){
die(“disallowed_table name. if your tables names contain other characters, consider renaming them.”);
}//end if

if (!($conn2=mysql_connect(‘localhost’, ‘root’, ”)))  {
printf(“error connecting to DB by user = $username and pwd=$pwd”);

$db2=mysql_select_db(‘edward_hootofloot’,$conn2) or die(“Unable to connect to local database”);
$sql = “select * from $table”;
$result = mysql_query($sql) or die (“Can’t complete query because “.mysql_error());

if (($result) && (mysql_num_rows($result)>0)){

//set the path and file name
$filename = “Ad_Details_”.date(“d_M_Y”);

if (!$handle = fopen($filename, ‘w’)) {
echo “Cannot open file ($filename)”;

while ($rows = mysql_fetch_array($result)){
$fields = mysql_num_fields($result);
$content = “”;
//calc the length of the line (number of elements)
for($x = 0; $x < $fields-1; $x++){

$content .= $rows[$x] . ”    “;

echo “<br>”;
$content = substr($content, 0, strlen($content)-2). “\n”; //remove the last pipe as its not needed and adds the new line character

// Write $content to our opened file.
if (fwrite($handle, $content) === FALSE) {
echo “Cannot write to file ($filename)”;
}//end while


//call the function to force the download the users computer

}//end if

}//end if
function force_download($file)
if (isset($file)) {
header(“Content-type: application/force-download”);

header(“Content-Transfer-Encoding: Binary”);
header(“Content-length: “.filesize($file));
header(‘Content-Type: application/octet-stream’);
//header(“Content-disposition: attachment; filename=””.basename($file).”””);
header(‘Content-Disposition: attachment; filename=”‘ . $file . ‘”.txt’);
} else {
echo “No file selected”;
} //end if

}//end function

function show_form()
echo “<html><body><h2> Table Data Exporter </h2>
<h4>Creates a pipe delimited file of the table contents.</h4>
<br><br><form name=myform method=post>
Table Name:<input type=text name=mytable>
<input type=submit name=submit value=Submit>


click here for more details :

Note : TXT file is stored at that location where this script is stored.

If you have any question or any query regarding this, please comment on this.

Thank you !!

  • Nic

    Hi, I am very new to php, can you explain how and where I would run this script to export the data?