HTML to CSV PHP - php

I've been trying to export MySQL fields to CSV and can get all them exporting correctly except the filed which contains HTML.
My MySQL table is made up as follows:
Name: Address: Profile:
Name is simply text as with address, but profile is HTML
My array is:
$array = array ( array ( "Name" => "$name", "Address" => "$address", "Profile" => $profile )
);
Made using:
$name = $info['name'];
$address = $info['address'];
$profile = $info['profile'];
I have a "Tab" \t delimiter and every exports into the CSV correctly bar the HTML which I would like to keep as pure HTML but in one Excel field, at the moment is splits across multi rows and fields.
CSV code is as follows:
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");
$titleArray = array_keys($array[0]);
$delimiter = "\t";
$filename="profiles.xls";
foreach ($array as $subArrayKey => $subArray) {
$dataRowString = implode($delimiter, $subArray);
print $dataRowString . "\r\n";
}
Any help or advise would be highly welcomed.

You need to escape the field values. You can use fputcsv:
$stdout = fopen('php://stdout', 'w');
fputcsv($stdout, $subArray, "\t");
$filename="profiles.xls";
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");
$titleArray = array_keys($array[0]);
$delimiter = "\t";
$stdout = fopen('php://stdout', 'w');
foreach ($array as $subArrayKey => $subArray) {
fputcsv($stdout, $subArray, $delimiter);
}

Related

Array to csv download in PHP

I am trying to turn my array in PHP into a csv to download.
Currently the array looks something like this
Array[0] = "Name,age,ID"
Array[1] = "Alex,26,1"
Array[2] = "Ryan,12,2"
Array[3] = "Steph,56,7"
etc
I was unsure how to make this download as a csv, where each array position is its own line is csv obviously.
I set the headers to the following :
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
then I tried to echo each element of the array, hoping this would work. as follows:
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
foreach ($lines as &$line) {
echo $line;
}
Where $lines was my array.
However it did all one line in the csv. Is there a way I can turn this array to print properly in csv?
You have to add a newline
echo $line . "\n";
Even better
echo $line . PHP_EOL; //constant for correct line-ending depending on OS.
One of solution is fputcsv function.
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
$output = fopen('php://output', 'w');
foreach ($lines as $line) {
$row = explode(',', $line);
fputcsv($output, $row);
}
fclose($output);

How do I get MySQL table entities in excel

What I have done is get the data from MySQL to excel in csv format but I am not getting the entities of that table like if I have a table member having these 3 entities
memberid membername memberemail
I am getting the data of these entities like
1 alishah test#test.com
What I want is when I download an excel it gets header with it like
memberid membername memberemail
1 alishah test#test.com
What I did for excel is
<?php
$selectUserData = "SELECT * FROM tbl_member";
$export = $conn->query($selectUserData);
$fp= fopen('php://output', 'w');
foreach ($export as $fields)
{
fputcsv($fp, $fields);
}
header("Content-Type: text/csv;charset=utf-8" );
header("Content-Disposition: attachment;filename=member.csv");
header("Pragma: no-cache");
header("Expires: 0");
?>
Simply write a line with the column headers before writing the data to the csv.
<?php
$selectUserData = "SELECT * FROM tbl_member";
$export = $conn->query($selectUserData);
$fp = fopen('php://output', 'w');
fwrite($fp,'"memberid","membername","memberemail"'."\n");
foreach ($export as $fields)
{
fputcsv($fp, $fields);
}
header("Content-Type: text/csv;charset=utf-8" );
header("Content-Disposition: attachment;filename=member.csv");
header("Pragma: no-cache");
header("Expires: 0");
?>

PHP simple csv export is not work with array in Wordpress Plugin

I'm tring to export csv file from the PHP array in wordpress plugin.
However when I put die inside the foreach the CSV file created with the first elements of array. otherwise CSV file not generate.
Array :
Array
(
[0] => Array
(
[fname] => test name 1
[lname] => lname 2
)
[1] => Array
(
[fname] => test name 2
[lname] => lname
)
)
Code :
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=loyalty.csv');
$filename = "loyalty.csv";
$handle = fopen('php://output', 'w');
fputcsv($handle, array('First Name','last Name'));
foreach($loUsers as $row) {
fputcsv($handle, $row);
//die;
}
fclose($handle);
When the die is not commenting nothing will happen but if I put but csv file created with first element.
Seems the code is correct and can't find the issue.
Thanks
Try this:
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=User_Sample.csv");
// Disable caching
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1
header("Pragma: no-cache"); // HTTP 1.0
header("Expires: 0"); // Proxies
$data = array(
array('User Type', 'User Name', 'Category', 'Mobile Number'),
array('I', 'Anuj Kumar', 'Building Construction', '8500000001'),
array('I', 'Arvind Kumar', 'Carpentary', '8500000002'),
array('I', 'Mridul Ohja', 'Civil Engineering', '8500000003'),
array('I', 'Naman Kumar', 'Electrical', '8500000004'),
array('I', 'Sumati', 'Faucets', '8500000005'),
array('I', 'Anjum', 'Flooring Tiles / Marbles', '8500000006'),
array('I', 'Rajat', 'Painting', '8500000007'),
array('C', 'Arvind', 'Plumbing', '8500000008'),
array('C', 'Rohit', 'Sanitaryware', '8500000009'),
array('C', 'Gaurav', 'Soil Test Analyst', '8500000010')
);
$output = fopen("php://output", "w");
foreach ($data as $row) {
fputcsv($output, $row); // here you can change delimiter/enclosure
}
fclose($output);
It works for me.
Check this out its easy:
<?php
session_start();
include_once('includes/config.php');
$filename = "testing-exports.csv";
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");
$insquery = "SELECT username FROM r_institution where status=1";
//$exportstmt = $conn->query($insquery);
$insresults = $conn->query($insquery);
//$insresults = mysqli_fetch_assoc($exportstmt);
foreach ($insresults as $rs) {
$row = array();
$row[] = stripslashes($rs["username"]);
$content[] = $row;
}
$content = array();
$title = array("Institution Emails");
foreach ($insresults as $rs) {
$row = array();
$row[] = stripslashes($rs["username"]);
$content[] = $row;
}
$output = fopen('php://output', 'w');
fputcsv($output, $title);
foreach ($content as $con) {
fputcsv($output, $con);
}
?>

Read and write using fgetcsv and fputcsv

I have a 3rd party source from where I am getting "csv" file. I wrote it inside a quote because it says it's a csv file but basically it's not.
So I am taking that main source file then reading and putting the data in a "PROPER" csv file.
The read and write is fine but the problem is when it saves the properly quoted data is writing on the script file itself.For example if the my php file name is "fixcsv.php" then I am getting the downloadable file as "fixcsv.php".
My code
$headings = array('HID');
$handle = fopen("MonC1.csv", "r");
$data = fgetcsv($handle, 0, ";",'"');
$fh = fopen('php://output', 'w');
ob_start();
fputcsv($fh, $headings);
// Loop over the * to export
if (! empty($data)) {
foreach ($data as $item) {
// echo $item;
fputcsv($fh, array($item));
}
}
$string = ob_get_clean();
$filename = 'csv_' . date('Ymd') .'_' . date('His');
// Output CSV-specific headers
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment filename=\"$filename.csv\";" );
header("Content-Transfer-Encoding: binary");
exit($string);
Any help is highly appreciated. Thanks in advance.
Your Content-Disposition has a semi-colon in the wrong place (per the spec). Should be:
header("Content-Disposition: attachment; filename=\"$filename.csv\" );

Laravel 3 create Text (CSV) file

Hello I am trying to grab all the emails from the database, then output them into a text (comma separated) file. Here is what I have done but does not work:
public function get_textfile() {
$emails = Staff::get('email');
header("Content-type: text/csv");
header("Cache-Control: no-store, no-cache");
header('Content-Disposition: attachment; filename="filename.txt"');
$stream = fopen("php://output", 'w');
foreach($emails as $email) {
fputcsv($stream, $email, ',');
}
fclose($outstream);
}
return (something)?
getting this: Error 6 (net::ERR_FILE_NOT_FOUND): The file or directory could not be found.
This is my route:
Route::get('textfile', array('as' => 'textfile','uses' => 'admin#textfile'));
try file_put_contents($filename, implode(',', Staff::get('email')));
Collect all of your data into a string and then output it like this:
$data = '';
foreach ($emails as $email)
{
// If you want 1 email per line
$data .= '"'.$email.'"'.PHP_EOL;
// If you want all emails on 1 line
$data .= '"'.$email.'",';
}
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename=My Cool File.csv');
header('Pragma: no-cache');
header('Expires: 0');
echo $data;

Categories