$connection = Bitrix\Main\Application::getConnection();
$sqlHelper = $connection->getSqlHelper();
$sql = "SELECT
DATE_FORMAT(c.DATE_INSERT, '%Y-%m-%d %H:%i:%s') AS DATE_INSERT,
c.EMAIL,
GROUP_CONCAT(l_name.NAME SEPARATOR ', ') as groups,
c.NAME
FROM b_sender_contact c
LEFT JOIN b_sender_contact_list l
ON (l.CONTACT_ID=c.ID)
LEFT JOIN b_sender_list l_name
ON (l.LIST_ID=l_name.ID)
GROUP BY c.ID";
$recordset = $connection->query($sql);
$orders = [];
$fp = fopen($_SERVER["DOCUMENT_ROOT"] . '/emails.csv', 'w');
while ($record = $recordset->fetch()) {
fputcsv($fp, $record);
// echo "<script>console.log(" . json_encode($record) . ");</script>";
// echo $record['EMAIL'];
// echo '<br>';
}
fclose($fp);