Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unable to generate .csv file : PHP

Tags:

php

csv

Actually I have no idea how to generate a .csv file.I have gone through various e-notes but still not getting.

What I want to do?

I have written a piece of code to echo "partner_name" and "link" but these need to be put into a formDetails.csv file.

$result = mysql_query(
    "SELECT form_id, partner_name 
     FROM `ef_kabaadkhana`.`ef_form_master_v1` 
     WHERE active = 1 AND listed = 1;"
);

while ($formDetails = mysql_fetch_assoc($result)) {
    $partner_name       = $formDetails['partner_name'];
    $formId             = $formDetails['form_id'];
    $slugifyPartnername = slugify($partner_name);
    $partner_link       = "http://myforms.com/form/{$formId}/{$slugifyPartnername}";
    echo $partner_name . '=>' . $partner_link, "\n";
}

function slugify($text) {
    $text = preg_replace('~[^\\pL\d]+~u', '-', $text);
    $text = trim($text, '-');
    if (function_exists('iconv'))
        $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
    $text = strtolower($text);
    $text = preg_replace('~[^-\w]+~', '', $text);
    if (empty($text))
        return 'n-a';
    return $text;
}

What it does?

It simply takes form_id and partner_name from ef_form_master_v1 table. The $partnerName and $partnerlink are defined and displayed accordingly.

But Instead of echoing $partnerName and $partnerlink, I want to put these array of parameters in a CSV file named formDetails.csv.

like image 353
Sam Avatar asked Sep 01 '26 06:09

Sam


1 Answers

The documentation on fputcsv is pretty clear, however I will provide an example below:

$handle = fopen('/path/to/formDetails.csv', 'w');

while(<your query loop>) {
    $write = array($partner_name, $partner_link);
    fputcsv($handle, $write);
}

fclose($handle);
like image 53
phpisuber01 Avatar answered Sep 04 '26 21:09

phpisuber01



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!