Criando CSV com PHP
E ai galera beleza?
Então... eu to aqui querendo saber alguma maneira melhor de criar meus CSVs com PHP
Eu crio assim com zend:
private function _createCsvFile($version, $id, $type)
{
$this->_db = Zend_Registry::get('db');
$tables[] = "fm_block";
$data = array();
foreach ($tables as $table)
{
$filename = "RSVP_users_list.csv";
header("Content-Type: application/csv; charset=iso-889101");
header('Content-Disposition: attachment; filename="'.$filename.'"');
if($type == 1) {
$sql = "SELECT u.firstName, u.lastName, u.email, e.title, b.is_attending, b.additional_information
FROM fm_users u
RIGHT JOIN fm_block b ON u.uid = b.userID
RIGHT JOIN fm_events e ON b.event = e.eid
WHERE b.event = $id";
}else {
$sql = "SELECT u.firstName, u.lastName, u.email, e.title
FROM fm_users u
RIGHT JOIN fm_block b ON u.uid = b.userID
RIGHT JOIN fm_deals e ON b.deal = e.dealid
WHERE b.additional_information = 1 AND b.deal = $id";
}
$result = $this->_db->fetchAll($sql);
$i = 0;
foreach ($result as $row)
{
$i++;
if ($i==1)
{
print implode(self::INI_SEPARATOR, array_keys($row))."\n";
}
if($version == 1){
print $this->utf8FixEntities(htmlentities(implode(self::INI_SEPARATOR, str_replace(',', ' ', $row)),ENT_COMPAT,'UTF-8'))."\n";
}else {
print $this->utf8Fix($this->entityFix(htmlentities(implode(self::INI_SEPARATOR, str_replace(',', ' ', $row)),ENT_COMPAT,'UTF-8')))."\n";
}
}
}
}
E crio assim com wordpress:
function toc_insider(){
global $wpdb;
$root = WP_CONTENT_DIR . "/plugins/buffalo_bills";
$folder = get_theme_root();
if(file_exists($folder."/buffalo-bills/archive.zip")){
unlink($folder."/buffalo-bills/archive.zip");
}
$filename = $root.'/become_insider.csv';
$fileToZip = "become_insider.csv";
if(file_exists($filename)){
unlink($filename);
}
$fp = fopen($filename, "w");
$res = mysql_query("SELECT * FROM wp_bb_insider");
// fetch a row and write the column names out to the file
$row = mysql_fetch_assoc($res);
$line = "";
$comma = "";
foreach($row as $name => $value) {
$line .= $comma . '"' . str_replace('"', '""', $name) . '"';
$comma = ",";
}
$line .= "\n";
fputs($fp, $line);
// remove the result pointer back to the start
mysql_data_seek($res, 0);
// and loop through the actual data
while($row = mysql_fetch_assoc($res)) {
$line = "";
$comma = "";
foreach($row as $value) {
$line .= $comma . '"' . str_replace('"', '""', $value) . '"';
$comma = ",";
}
$line .= "\n";
fputs($fp, $line);
}
fclose($fp);
$size = filesize($filename);
$file = @fopen($filename, 'rb');
require_once(ABSPATH . 'wp-admin/includes/class-pclzip.php');
$archive = new PclZip($folder."/buffalo-bills/archive.zip");
$v_list = $archive->create("$filename",
PCLZIP_OPT_REMOVE_ALL_PATH,
PCLZIP_OPT_ADD_PATH, 'archive');
if ($v_list == 0) {
print("Error : ".$archive->errorInfo(true));
}
?>
<h2>Become insider users </h2>
<a href="/wp-content/themes/buffalo-bills/archive.zip">Click here</a> to download all users from become insider
<?php
}
Os dois funcionam maravilhsamente bem.
Não tenho problema algum com o código... o CSV abre tranquilamente no excel e tals...
Agora tenho 1 problema
no Excel windows você tem que separar os valores com ; (ponto e virgula)
E no MAC com , (virgula)
Eu queria saber se existe alguma maneira de detectar... ou criar um separador que funcione tanto para MAC como para PC
Pois se to no meu PC e crio o sistema... acabo criando para minha visualização e ai quando vou para o escritório e trabalho no MAC e não consigo abrir corretamente os CSV's
Eu tentei criar tbm uma versão em XML que sei que o excel lê... mas ele fica enxendo minha paciencia com espaços em branco ou URLS
Alguem saberia me dizer como criar um XML seguro para excel?
Bom fico por aqui com essas dúvidas.
Lembrando que ambos os códigos funcionam perfeitamente bem no Wordpress e no ZEND e da pra fazer manual tbm se quiser...
Abraços
Discussão (2)
Carregando comentários...