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
Related
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
));
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 am running an API, the response of this API is returning response in comma separated values.
I am returning response in $result.
Response:
lmd_id,status,title,description,code,categories,store,url,link,start_date,expiry_date,coupon_type 106864,new,"Gift Vouchers worth ₹2000 # for just ₹999","Get it for just ₹999",,"Gift Items","ABC Company",http://example1.com,http://example2.com,"2016-04-07 00:00:00","2016-05-01 00:00:00",sale
Below are the headers in response:
lmd_id,status,title,description,code,categories,store,url,link,start_date,expiry_date,coupon_type
Code I have tried:
function str_putcsv($result) {
# Generate CSV data from array
$fh = fopen('php://temp', 'rw'); # don't create a file, attempt
# to use memory instead
# write out the headers
fputcsv($fh, array_keys(current($result)));
# write out the data
foreach ( $result as $row ) {
fputcsv($fh, $row);
}
rewind($fh);
$csv = stream_get_contents($fh);
fclose($fh);
return $csv;
}
With the code above I am not able to find where this code is generating CSV.
Another code:
$fp = fopen('data.csv', 'w');
foreach($data as $line){
$val = explode(",",$line);
fputcsv($fp, $val);
}
fclose($fp);
Above code is generating file on FTP but there is no data in it. It is generating blank CSV.
I want to convert this response into CSV file and put it on a FTP or in the same directory.
You can just put everything in an array. And use int fputcsv ( resource $handle , array $fields [, string $delimiter = "," [, string $enclosure = '"' [, string $escape_char = "\" ]]] )
Example from php.net:
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);
$fp = fopen('path/to/file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
read more about fgetcsv here
How should I use tabulate?
$naglowek = "ID,\t Imię,\t Nazwisko,\t Data urodzenia,\t Miasto,\t EMAIL";
$naglowek = explode(";",$naglowek); // header
fputcsv($fp, $naglowek);
while($r = $result->fetch_assoc()){
$ciag = '';
$ciag = $r['id'].','.$r['name'].','.$r['surName'].','.$r['dateOfBirth'].','.$r['city'].','.$r['email'];
$ciag = explode(";",$ciag);
fputcsv($fp, $ciag,"\t");
}
I added "\t" but it isn't working.
Below is question, what somebody answered.
I made a CSV generator for my client. It should get data from DB (mysqli).
The code is :
while($r = $result->fetch_assoc()){
$someVariable = $r['id'].','.$r['name'].','.$r['surName'].','.$r['dateOfBirth'].','.
$r['city'].','.$r['email'];
}
It is working. But I go to next step to use a function fputcsv. It is from PHP5.
This is how my DB looks:
In PHPManual fputcsv is using like:
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);
How can I use my data to this array ? My data will be from DataBase and will be generated dynamically by the loop above.
You can do that in this way:
$fp = fopen('out.csv', 'w');
while($r = $result->fetch_assoc()){
fputcsv($fp, $r);
}
fclose($fp);
For each line that fetch from the database, it will include in out.csv file.
I have a script that copys results from a table and saves it in a csv format. Everything is running fine with the script except that it does not recognize \n and just inputs it in the last cell like blahblah\r\n.
I have these lines currently but neither situation is creating the new line...-
$csv_output .= "$lastName,$firstName,$agentMLSID,$agentBoard,$directOffice,$directOfficeExtension,$voicemail,$mobile,$email,$officeName ".PHP_EOL;
$csv_hdr = "lastname,firstname,mslid,board,directline,ext,vm,mobile,email,office";
$csv_hdr .= "\n";
fputcsv() is what you need.
<?php
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789')
);
$fp = fopen('file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
?>
Output (file.csv):
aaa,bbb,ccc,dddd
123,456,789