How to generate csv file with ajax call in php - php

I am working with PHP AJAX DATATABLE (in drupal). I am making a function to generate csv file of the table record.
I create a button to click (in html) to access that link (or if i am calling it by url. )
I did it and my function(php Function) is working fine.
But how can i create a csv on depends on searched values ? I dont want to refresh my page and i think ajax call help me.
But how to handle my csv file creation function in ajax call.
My php function
/* testing the excel output */
function export_to_excel_page() {
//testing
$filename = "file_name.csv";
$row_array = db_query('SELECT recipient_name , year , title , sector , region , commitment_million_inr FROM {#######} ');
drupal_add_http_header('Content-Type', 'text/csv; utf-8');
drupal_add_http_header('Content-Disposition', 'attachment; filename=' . $filename);
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('recipient_name', 'year', 'title', 'sector','region','commitment_million_inr' ));
foreach($row_array as $key => $value) {
fputcsv($output, (array)$value);
}
}

If you are using an on click event you can use the JQuery $.get function to do what you want.
//change #button to whatever id or class name you are using in your html
$("#button").on("click",function(){//begin on click event
$.get("place path to the csv here",function(data){//begin function
//Use the data parameter passed in to the function to manipulate(parse)
//your data returned from your csv file here.
//if you want to see if there is a string inside of the data
//indexOf returns -1 if the item is not found
//Check to see if the searchterm is found or is not equal to -1
if(data.indexOf("searchterm") !== -1){//begin if then
//Do something if you find the searchterm string.
}//end if then
//if they are comma seperated values you can first
//turn the csv into an array
var csv = data.split(",");
//loop through the array do whatever you need to do
for(var i =0; i < csv.length; i++){//begin for loop
//if the array index equals the string something
if(csv[i] === "something"){//begin if then
//do something like turn the csv into an undordered list
}//end if then
}//end for loop
});//end function
});//end on click event

Related

How to split csv data in two parts.?

Is it possible to export csv data in to two parts:
From the below image i have two things to be considered
1. summery
2. Detail information
I worked with only 2nd type is it possible to do like 2 batches(like shown in image)..?
please suggest any alternate idea if you got.
Example:
summary header
$titleSummery = array('Course Name','Average watched','semi watched','notwached','sudents attempted','sudents notattempted','Total students','Branch','passout');
/*summery data */
Details header
$titleDetail = array('student','passout','branch','percentage watched','student email');
/*Details data */
In this case how can i export the data..?
$output = fopen('php://output', 'w');
fputcsv($output, $title);
foreach($data as $k=>$res){
fputcsv($output,$res);
}
You need to prepare array for each line. see my inline comments.
$titleSummery = array('Course Name','Average watched','semi watched','notwached','sudents attempted','sudents notattempted','Total students','Branch','passout');
$titleSummeryData = array('Number System','50%','40%',....); // fill remaining data.
$output = fopen('php://output', 'w');
// put first table
foreach($titleSummery as $key=>$val){
fputcsv($output,array($val,$titleSummeryData[$key]));
}
// begin second table
// put all title/header
fputcsv($output,$titleDetail);
// For second table i assume that you have data in 2D array
foreach($titleDetailsData as $row){
fputcsv($output);
}
fclose($output);
You direction is good, you just need to understand that each call to fputcsv prints a line, so you'll need to call it for each row in the first batch of data also, for example:
fputcsv($output,"course name","php for dummies");

Format txt file

I need to import csv file with php getcsv function but the file is not well formated and cannot import it. After uploading the file, I'd like to delete all " inside the file to have a proper file with ; for each field.
This is an example of my file:
"DENO;NAME;SURNAME;""BIRTH"";""ZIP"";CITY;E-MAIL;TELEPHONE"
"M;DAVID;BON;""1959-02-12 00:00:00"";75009;PARIS;email#gmail.com;010000000"
"M;DOE;JHON;""1947-02-02 00:00:00"";75008;PARIS;email#gmail.com;060000000"
"M;DAVE;Philippe;""1950-01-01 00:00:00"";75002;""PARIS"";email#gmail.com;070000000"
I think I would need to read each line of the file,and maybe use str_replace but I don't know how to write the new file...
Assuming you can get your code into a text string, you can just replace/remove the double-quotes. Then parse the text and get it into a format that will support fputcsv().
When writing the folder, be sure to check that your user has permissions to write to this folder (for example if the parent folder has permissions drwxr-xr-x, you can fix it with chmod g+w folder_name).
<?php
// sample text to parse
$some_text = '"DENO;NAME;SURNAME;""BIRTH"";""ZIP"";CITY;E-MAIL;TELEPHONE"
"M;DAVID;BON;""1959-02-12 00:00:00"";75009;PARIS;email#gmail.com;010000000"
"M;DOE;JHON;""1947-02-02 00:00:00"";75008;PARIS;email#gmail.com;060000000"
"M;DAVE;Philippe;""1950-01-01 00:00:00"";75002;""PARIS"";email#gmail.com;070000000"';
// remove quotes
$final_text = str_replace('"', '', $some_text);
// create array of rows by searching for new lines
$data = str_getcsv($final_text, "\n");
// create an empty array to save our final csv data
$final_csv = array();
// loop thru the array and save to the final csv data
foreach ($data as $value) {
// before saving to final csv data, split row into individual column items
$value_array = explode(";", $value);
$final_csv[] = $value_array;
}
// helper debugger to show data before writing it
echo "<pre>";
print_r($final_csv);
echo "</pre>";
// create a new file for writing or open and truncate to 0
$fp = fopen('file.csv', 'w');
// write to file from final csv data
foreach ($final_csv as $fields) {
fputcsv($fp, $fields);
}
// close file
fclose($fp);
?>

CSV data from interface to MySQL with PHP

I have this data from a real time interface call of an url:
"DATETIME";"ACTION";"ACTIONTEXT";"POSITION";"AREA";"DRIVERKEY";"DRIVERNAME";"CAR";"LAT";"LON";
"21.05.2013 10:59:00";"G";"Arbeitsende";"";"20037100 ARCUS Cottbus";"0000161395E7";"Süsse, Daniel";"Neubuchung";"0";"0";
"21.05.2013 19:07:00";"G";"Arbeitsende";"";"20037100 ARCUS Cottbus";"0000161395E7";"Süsse, Daniel";"Neubuchung";"0";"0";
"27.05.2013 05:38:05";"K";"Arbeitsbeginn";"D-02625 Bautzen Hanns-Eisler-Straße 10";"";"0000161395E7";"Süsse, Daniel";"BZ-DK 101";"51.17421";"14.45179";
"27.05.2013 06:04:25";"K";"Arbeitsbeginn";"D-02733 Cunewalde Gewerbegebiet Roßkaupe 11";"";"00001613B355";"Wypior, Andreas";"BZ-DK 11";"51.09184";"14.53524";
"27.05.2013 06:20:26";"K";"Arbeitsbeginn";"D-02733 Cunewalde Gewerbegebiet Roßkaupe 11";"";"000016127326";"Henze, Jens";"BZ-DK 55";"51.09194";"14.53433";
"27.05.2013 06:52:33";"K";"Arbeitsbeginn";"D-97792 Riedenberg";"";"000016139436";"Rother, Thomas";"BZ-DK 260";"50.3171";"9.845136";
I have tried different functions to get this data directly from the url call imported (structured) to a MySQL database via PHP but I always end up having the entire data in one field, not separated like the following:
DATETIME: 21.05.2013 10:59:00
ACTION: G
ACTIONTEXT: Arbeitsende
...etc
Hope you can help/teach me solving this.
The PHP part for saving the csv data (text in body-element) in a temporary csv:
$fp = fopen('$url', 'w');
$delimiter = ';';
$headers = array('DATETIME', 'ACTION', 'ACTIONTEXT', 'POSITION');
fputcsv($fp, $headers, $delimiter);
foreach ($worker as $worker) {
$fields = array($worker->...);
fputcsv($fp, $fields, $delimiter);
}
fclose($fp);
I really do not know how to grab this text (csv-formated) directly from the site to have it correctly imported to a MySQL db.
foreach ($worker as $worker)
This is looking ugly and "shadows" the $worker array from the global scope with a local variable of the same name in the scope of the loop. In the loop (and worse as that: even after the loop), the original $worker array has been replaced by one of its elements.
Its probably just a typo, but if it is from real code, please consider choosing unique variable names.

FLASH AS2 and PHP variables

My Flash movie reads and sends data to a PHP file in a free server. It seems ok for Flash to read variable values from a text file (which is managed by a PHP file) if they are wrote in this way: &variable = value&, I have no problem with that.
But my PHP file, pre-treated (by some mathematical functions) data sent by Flash and then, updates the values in the text file, that is my intention but I can't accomplish it.
Suppose I want to update a counter ( it counts how many times the data were updated):
in the text file I have &counter=0& (initial value) and if I put in the PHP file:
<?php
$fp = fopen("jose_stats.txt", "r");// I guess with it, I've read all the variables and values
// one of them is the variable &counter.
fclose($fp);
$toSave = "&counter=&counter+1&\n";
$fp = fopen("jose_stats.txt", "w");
if(fwrite($fp, "$toSave")) {
echo "&verify=success&"; //prints to screen &verify=success which flash will read
//and store as myVars.verify
} else { // simple if statement
echo "&verify=fail&"; //prints to screen &verify=fail which flash will read and
//store as myVars.verify
}
fclose($fp);
?>
but then, I check my text file and it has &counter=&counter+1& line :( and not the expected &counter =1&.
Please, give me and advise. Thank you.
Why not use JSON?
Just store the data in JSON format:
$count = 1;
$toWrite = array( 'count' => $count );//put other data into this array if you want
//encode it
$toWrite = json_encode( $toWrite );
//and now write the data
To decode it in flash, import the JSON class:
An example of JSON in as2 using the JSON.as class:
try {
var o:Object = JSON.parse(jsonStr);
var s:String = JSON.stringify(obj);
} catch(ex) {
trace(ex.name + ":" + ex.message + ":" + ex.at + ":" + ex.text);
}
So just import the class, and run JSON.parse( yourPhpResponse );.
Also, the reason for why you're seeing &counter=& in the text file is because you're storing it like that: $toSave = "&counter=&counter+1&\n";.

Check for header in csv and ignore header in php

I would like to check if csv file contain a header and ignore the header.
I have to do a check if the first column is not a character
csv file has format : avgTemperature, minTemperature, maxTemperature
$f = fopen("./uploads/" .$filename, "r");
$string = "avgTemperature";
if (fgetcsv($f)==$string){
// read the first line and ignore it
fgets($f);
}
I assume your complete code uses a loop (while or for).
As such, you have a few options.
Simply skip the first row always.
Use logic to test for the header row then skip.
Either way, continue is the key piece.
PHP pseudo code:
while (…) {
if ($row == $header_row) {
continue;
}
// data rows
}
UPDATE
The logic for determining if the first row is a header row seems like a better solution in your case. You could use the following to test for that.
if ($row[0] == 'avgTemperature') {
// header row
}
Note: This makes the assumption that the first column of data is avgTemperature and it's header is avgTemperature. Adjust as necessary.
Going from your comment, and from the idea that the actual data is temperatures (i.e. numeric data), if you do have headers, then they will be text strings and not numbers. Therefore you can do something like this:
$f = fopen("./uploads/" .$filename, "r");
if(!($data = fgetcsv($f))) {
return; //most likely empty file
}
if(!is_numeric($data[0])) {
//this is your header line - skip it - and read the next line
$data = fgetcsv($f);
}
while($data) {
//process a line of data
...
//and read the next line
$data = fgetcsv($f);
}
EDIT: An alternative version of the last loop would look like this:
do {
//process a line of data
...
}
while ($data = fgetcsv($f));

Categories