kinlane
2/25/2016 - 12:02 AM

Export ClinicalTrials.gov Database As CSV

Export ClinicalTrials.gov Database As CSV

<?php

$host = "[your database server";]
$database = "[your database name]";
$user = "[your user]";
$pass = "[your password]";

// database connection
mysql_connect($host, $user, $pass) or die ('cannot connect to the database: ' . mysql_error());
mysql_select_db($database) or die ('cannot select database: ' . mysql_error());

// function for creating default 200 OK
function getOK($table)
	{
		
	$R = array();
	$R['description'] = $table . " response";		
	$R['schema'] = array();
	
	$S = array();
	$S['type'] = "array";
	
	$I = array();
	$I['$ref'] = "#/definitions/" . $table;
	
	$S['items'] = $I;
	
	$R['schema'] =  $S;			
	
	$ok = new stdClass;
	$response = "200";
	$ok->$response = $R;		
		
	return $ok;	
	}

$Spec_Name = str_replace("_"," ",$database);
$Spec_Name = ucwords($Spec_Name);

// loop through table + fields
$loop = mysql_query("SHOW tables FROM " . $database) or die ('cannot select tables');

while($table = mysql_fetch_array($loop))
{
	
	// We will need to identif
	$this_key = "";
	
	// The table name
    $table = $table[0];
	
	$header = "";
	$data = "";
	
	$select = "SELECT * FROM `" . $table . "`";
	
	$export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );
	
	$fields = mysql_num_fields ( $export );
	
	for ( $i = 0; $i < $fields; $i++ )
	{
	    $header .= mysql_field_name( $export , $i ) . "\t";
	}
	
	while( $row = mysql_fetch_row( $export ) )
	{
	    $line = '';
	    foreach( $row as $value )
	    {                                            
	        if ( ( !isset( $value ) ) || ( $value == "" ) )
	        {
	            $value = "\t";
	        }
	        else
	        {
	            $value = str_replace( '"' , '""' , $value );
	            $value = '"' . $value . '"' . "\t";
	        }
	        $line .= $value;
	    }
	    $data .= trim( $line ) . "\n";
	}
	$data = str_replace( "\r" , "" , $data );
	
	if ( $data == "" )
	{
	    $data = "\n(0) Records Found!\n";                        
	}	

	if($table!='clinical_study')
		{
		$file_name = $table . ".json";
		$writefile = "files/" . $file_name;
		echo "writing " . $writefile . "<br />";
		$myfile = fopen($writefile, "w") or die("Unable to open file!");
		fwrite($myfile, $data);
		fclose($myfile);
		}
	} 
?>