I have a list of users and I want to export it as a CSV file. I binded the button to an Angular controller.
HTML
<a class="btn btn-secondary-icon" href="" ng-click="csv()">Download CSV</a>
JS
$scope.csv = function() {
$scope.export.cols = _.keys(_.pick($scope.data.columns, function(col) {
return parseInt(col.checked) === 1;
}));
$http({
url: $scope.dataUrl,
data: $.param({
export: 1,
csv: $scope.export
}),
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(data) {
$rootScope.$broadcast('ErrorOnResponse', data);
if (data.csv) {
Download.download(
'yarooms-report-' + moment().format('YYYY-MM-DD') + '.csv',
'application/csv',
data.csv
);
Analytics.log(Analytics.event.EXPORT, Analytics.category.REPORTING);
}
});
};
My problem occurs when it comes to writing the PHP function that grabs the data from my DB. I even tried to export a simple hardcoded array, but it won't work. When I click the button, it makes a request to the server, but that's all, no downloaded file, nothing.
My testing PHP function:
$file = 'php://memory'
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);
$f = fopen($file, 'rw+');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
rewind($f);
$csv = stream_get_contents($f);
fclose($f);
Support_Model_Entity::logStat('Exported users CSV');
$this->jsonResponse(array(
'csv' => $csv
));
Related
[SOLVED] Had to split the download() method in 2, so it goes as generateCSV() and then getDownload().
After the the generation of the file, added this on sweetalert confirm button, which route points to getDownload().
preConfirm: () => {
window.location.href = "/customers/resale/filterToCSV/download";
}
After the user selects a few checkboxes for filtering a database table, the server writes to a CSV file, but it doesn't prompt the browser to download it.
route:
Route::get('/customers/resale/filterToCSV', 'Resale_customerController#getFilteredQueryResults');
blade view:
axios.get('/customers/resale/filterToCSV', {
params: {
dataFromClient: arrJson,
}
})
.then(function (response) {
Swal.fire({
icon: 'success',
title: '...',
text: '...',
})
console.log("Response (Filtered data to CSV): " + response.data);
});
controller:
public function getFilteredQueryResults(Request $request)
{
$arr = json_decode($request->dataFromClient, true);
$selection = $this->queryBuilderFromCheckboxSelection($arr);
$jsn = $selection->toJson();
$this->download($jsn);
}
which calls the download() method:
public function download($jsn)
{
$filePath = public_path().'\\file.csv';
$headers = array(
"Content-type" => "text/csv",
"Content-Disposition" => "attachment; filename=file.csv",
"Pragma" => "no-cache",
"Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
"Expires" => "0"
);
$jsonDecoded = json_decode($jsn, true);
$csvFileName = 'file.csv';
$fp = fopen($csvFileName, 'w');
foreach ($jsonDecoded as $row) {
fputcsv($fp, $row);
}
fclose($fp);
echo response()->download($filePath, $csvFileName, $headers);
return response()->download($filePath, $csvFileName, $headers);//->deleteFileAfterSend(true);
}
Any idea what am I missing? Thank you!
I have a line of data stored in $StripContent, when I echo $Stripcontent it shows
, , ,1 ,1415 ,Fietsen ,Omafietsen ,Avalon ,F 101 Oma Export 57cm Zwart , ,57 ,single speed remnaaf ,2017 ,21 ,249.00 ,135.00 ,19.50 ,8
However when I write $Stripcontent to the CSV file it only writes the first character instead of the whole line.
$Get_Content = file_get_contents($newname);
$StripContent = preg_replace("/<([a-z][a-z0-9]*)[^>]*?(\/?)>/i",',', $Get_Content);
$file = $newname;
$content = file($file);
foreach($content as $lineNumber => &$lineContent) {
if($lineNumber == 0) {
$lineContent .= $StripContent . PHP_EOL;
}
}
$allContent = implode("", $content);
file_put_contents($file, $allContent);
You can do it more direct with the $Stripcontent variable direclty, whithout the foreach part, like:
$Get_Content = file_get_contents($newname);
$StripContent = preg_replace("/<([a-z][a-z0-9]*)[^>]*?(\/?)>/i",',', $Get_Content);
$file = $newname;
$content = file($file);
file_put_contents($file, $Stripcontent);
This works if you want to store the stripContent string. I recomend you to wrap it between a try{...}catch() and check for folder permisions to avoid problems!
Or if you want to use the built-in function for CSV you can use fputcsv (offical documentation):
<?php
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);
$fp = fopen('file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
?>
Hope it helps!
I would like to be able to save the data I entered on a modal form to a file and return the data into an alert after submission.
This is the current AJAX I have.
$("#submit").click(function(){
$.ajax({
type: "POST",
url: "save.php",
data: $('#form1').serialize(),
success: function(r){
alert (r);
return false;
},
dataType: "html"
});
$('.modal').modal('show');
});
If you need to see save.php, here it is:
<?php
// check if a form was submitted
if( !empty( $_POST ) ){
// convert form data to json format
$data = array(
"name" => $_POST['name1'],
"branch_address" => $_POST['bAddress1'],
"officer_in_charge" => $_POST['officer1'],
"contact_number" => $_POST['contactN1']
); //processes the fields on the form
$json = json_encode( $data );
$file = 'entries.json';
// write to file
file_put_contents( $file, $json, FILE_APPEND);
?>
You just need to echo the json data from the PHP file, like this:
$json = json_encode( $data );
$file = 'entries.json';
// write to file
file_put_contents( $file, $json, FILE_APPEND);
echo $json;
This is how data is returned via ajax - you simply echo it out, then it should be captured by the script as the variable r in this case.
File save.php
<?php
// check if a form was submitted
if( !empty( $_POST ) ){
// convert form data to json format
$data = array(
"name" => $_POST['name1'],
"branch_address" => $_POST['bAddress1'],
"officer_in_charge" => $_POST['officer1'],
"contact_number" => $_POST['contactN1']
); //processes the fields on the form
$json = json_encode( $data );
$file = 'entries.json';
// write to file
file_put_contents( $file, $json, FILE_APPEND);
echo $json;
?>
Use echo $json; after the line file_put_contents( $file, $json, FILE_APPEND);
Is possible in a webpage create a button that export a specific table with PHP?
Example: I click the button "Export Contacts" and this call a function that return me a .csv file of the table "contacts", for example.
Here is the simple way to export the data to csv file. You can use this.
<?php
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);
$fp = fopen('file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
?>
Here is the link http://www.php.net/manual/fr/function.fputcsv.php
I have written a jQuery script that takes a JSON encoded list produced with this function is run in my theme's functions.php and creates a playlist for my jPlayer. However, the script only works when the $file variable is hard coded (for example, OH0400). But I need it to pick up the $file variable based on the page being loaded. But when I switch to this method (using URL), the script says the JSON is null.
I've run the script in multiple ways and the output between the hard coded $file and the variable based $file appear to be the same. Why do I get null when I make the switch?
Here's the PHP in my theme functions.php.
function MyjPlayerList(){
$url = explode( '/', $_SERVER['REQUEST_URI'] );
$file = strtoupper($url[2]);
//$file = 'OH0400';
$filename = '/dir/oralhistory/mp3files/'.$file.'*.mp3';
$FILES = glob( $filename );
foreach( $FILES as $key => $mp3 ) {
$mp3 = str_replace( '/dir/oralhistory/mp3files/', '',$mp3);
$FILE_LIST[ $key ][ 'title' ] = $mp3;
$FILE_LIST[ $key ][ 'mp3' ] = 'http://websiteurl.org/mp3files/'.$mp3;
}
$myjplayerdata = json_encode( $FILE_LIST );
header ( 'Content-type: application/json' );
echo $myjplayerdata;
exit;
die();
};
Here is my javascript:
ajax_player = function() {
jQuery('div#player').load('/js/player.html' , function() {
var cssSelector= {
jPlayer: "#jquery_jplayer_1",
cssSelectorAncestor: "#jp_container_1"
};
var playlist = [];
var options = {
swfPath: "/js/Jplayer.swf",
supplied: "mp3",
smoothPlayBar: true,
keyEnabled: true
};
var myPlaylist = new jPlayerPlaylist(cssSelector, playlist, options);
jQuery.ajax({
url: "/wp-admin/admin-ajax.php" ,
type: "POST",
dataType: "text json",
data: { action: "MyjPlayerList"},
success:(function(data) {
jQuery.each(data, function(index, value){
myPlaylist.add(value); // add each element in data in myPlaylist
console.log(data);
})
})//function (data) close
})//ajax close
})//jquery.load
}//ajax_player
Yes, check the character encoding you're using. That could be the problem.
thanks to the debugging of Marc,turns out that what I get when i run the script in page & what i get when I call the script w/ javascript are different. it's trying to glob admin-ajax.php instead of the URL.