Latest news
Home » PHP » Export large sql table data to csv using php(socialengine)

Export large sql table data to csv using php(socialengine)

//function to download  all users deatails to csv
public function downloadcsvAction()
{
ob_end_clean();
set_time_limit(0);
ini_set(‘memory_limit’, ‘2024M’);
$this->_helper->viewRenderer->setNoRender(true);
$this->_helper->layout->disableLayout();

$query=Engine_Db_Table::getDefaultAdapter()->select()
->from(‘engine4_users’,array(‘user_id’,’email’,’displayname’,’level_id’,’enabled’,’approved’,’intro_page’,’creation_date’))
->where(‘user_id <> ?’, 1)
->where(‘user_id not in (?)’, array(‘685′,’870′,’948′,’965′,’1031′,’1249′,’1279′,’1283’))
->where(‘user_id <> ?’, 6);

$aResult= $query->query()->fetchAll();
$fileName = “users_”.time().’.csv’;
header(‘Content-Type: application/csv’);
header(‘Content-Disposition: attachement; filename=”‘.$fileName.'”‘);
$f = fopen(‘php://output’, ‘w’) or show_error(“Can’t open php://output”);
$n = 0;
$line = array();
$array=array();
// foreach ($aResult[0] as $key => $value):
// if($key !=’enabled’ && $key !=’user_id’ ):
// $line[] = $key;
// endif;
// endforeach;

$line[]=’Email’;
$line[]=’Display Name’;
$line[]=’User Level’;
$line[]=’Approved’;
$line[]=’Intro’;
$line[]=’Signup Date’;
$line[]=’Phone Number’;
$line[]=’University’;

$array[] = $line;
foreach ($aResult as $row)
{
$line = array();
$subject = Engine_Api::_()->user()->getUser($row[‘user_id’]);
$fieldsByAlias = Engine_Api::_()->fields()->getFieldsvaluesByAlias($subject);
$phone = $fieldsByAlias[‘phone_no’];
$row[‘phone_no’] = $phone;
$universityId = $fieldsByAlias[‘university’];
$universityObj = Engine_Api::_()->fields()
->getFieldsOptions($subject)
->getRowMatching(‘option_id’, $universityId);

if( $universityObj ) {
$university = $universityObj->label;
}

$row[‘university’] = $university;
if(isset($row[‘level_id’])):
$row[‘level_id’]= Engine_Api::_()->getItem(‘authorization_level’, $row[‘level_id’])->getTitle();
else:
$row[‘level_id’]=’default’;
endif;
//
// if(isset($row[‘enabled’])):
// $row[‘enabled’]= ‘Enabled’;
// else:
// $row[‘enabled’]=’NO’;
// endif;

if(isset($row[‘enabled’]) && $row[‘enabled’]==1):
$row[‘approved’]= ‘Yes’;
else:
$row[‘approved’]=’No’;
endif;
unset($row[‘enabled’]);
if(isset($row[‘intro_page’]) && $row[‘intro_page’]==1):
$row[‘intro_page’]= ‘Yes’;
else:
$row[‘intro_page’]=’No’;
endif;
unset($row[‘enabled’]);
unset($row[‘user_id’]);
foreach ($row as $item):

$line[] = $item;
endforeach;
$array[] = $line;
}
foreach ($array as $user)
{

$n++;

if (!fputcsv($f, $user))
{
show_error(“Can’t write line $n: $user”);
}
}
fclose($f) or show_error(“Can’t close php://output”);

}

Leave a Reply

x

Check Also

How to print Codeigniter upload error

if you want to display errors on upload functionality in codeigniter. Use the following function ...