Print $name value in php - php

I am trying to print out the value of $name
yet it keeps printing out $name instead of the value here is the line:
header('Content-Disposition: attachment; filename="$name"');

PHP will only evaluate variables within double-quoted strings, not single quoted strings like you've used in your example.
Try this instead (if you need to output double quotes within a double-quoted string, you need to escape them with a backslash, otherwise PHP will treat them as the end-of-string delimiter):
header("Content-Disposition: attachment; filename=\"$name\"");

String interpolation does not happen between single quotes.
$name = "test";
echo "Value: $name"; // Value: test
echo 'Value: $name'; // Value: $name
More details here.

I think this is what your looking for
header('Content-Disposition: attachment; filename="'.$name.'"');
This would give a header like so:
Content-Disposition: attachment; filename="some_file_name.ext"
Hope this helps
Another way to do this is using sprintf
$header = sprintf('Content-Disposition: attachment; filename="%s"',$name);
header($header);
The sprintf is not really needed but there to show you how the variable would be placed into the header string

When dealing with single-quoted strings, always concatenate variables.
header('Content-Disposition: attachment; filename="' . $name . '"');

Try like this:
header('Content-Disposition: attachment; filename='.$name);

Why don't you just use " instead of ' like :
header("Content-Disposition: attachment; filename=$name");

header('Content-Disposition: attachment; filename='.$name);

Related

Convert html entities to unicode characters via php mysql csv export

In my MySQL database this is a sample of an HTML entity that I have:
Ú
When I export it through my script this is what I get:
ú
As you can see in my script I already have 'html_entity_decode' which should convert it appropriately to this (which is what I want):
Ú
Obviously, I am doing something wrong. I have exhausted other various scripts, solutions and otherwise have been trying to resolve this issue for over a day. Here is my PHP code:
$link = mysqli_connect("localhost", "user", "pass", "db");
$sql="SELECT * FROM wtf";
$result=mysqli_query($link,$sql);
if (!$result) die('Couldn\'t fetch records');
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header("Content-type: application/vnd.ms-excel");
header("Content-Encoding: UTF-8");
header('Content-Disposition: attachment; filename="results.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, array('Nome'));
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_map('html_entity_decode',array_values($row)), ',', '"');
}
die;
}
mysqli_close($link);
exit;
Could someone please help or at least point me in the right direction? Having taken on a project that requires European characters in the CSV results, it has been nothing less then a nightmare...
It sounds like you're probably using a newer version of PHP, which will default to "UTF-8" when html_entity_decode() is called. Maybe try something like this:
Instead of this:
fputcsv($fp, array_map('html_entity_decode',array_values($row)), ',', '"');
Try this:
fputcsv($fp, call_user_func_array('html_entity_decode', array(array_values($row), ENT_COMPAT, 'ISO-8859-1')), ',', '"');
The problem is caused by Excel misinterpreting the character encoding of your output.
An output like ú is an indication that a multi-byte character is being interpreted as two separate single byte characters. When instead of writing a string as CSV, you echo that same string, it is rendered correctly, so this means the problem is not in the string, as stored by PHP.
The header Content-Encoding: UTF-8 does not find its way to Excel, so in order to make Excel aware of the UTF-8 encoding, output a Byte Order Mark at the start of the output:
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header("Content-type: application/vnd.ms-excel");
header("Content-Encoding: UTF-8");
header('Content-Disposition: attachment; filename="results.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fwrite($fp, "\xEF\xBB\xBF"); // <--- add this
Secondly, things tend to also work better when you use a TAB character as separator instead of a comma, as in Europe some regional settings define the semi-colon as the separator (the comma being taken as decimal separator), and this will make all columns collapse into one. So write:
fputcsv($fp, array('Nome'), "\t", '"');
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_map('html_entity_decode',array_values($row)), "\t", '"');
}

Escape special characters for fputcsv();

Is there an easy way to escape special characters, double quotes and multiple spaces for fputcsv()? In short with a lot of regex i get data from a PDF and i build my array. Inside the array there are no html tags with the exception of <br> tag. Now the problem is that i have to escape chars like these:
Èàèìòù"\' <br>
This is the messy output that i have now:
<br> instead of <br>
� instead of È, ò, à, ', "
Lot of ������� where there are multiple spaces which i don't want
I'm using this code:
$fichier = 'file.csv';
header("Content-Type: text/csv;charset=UTF-8" );
header("Content-Disposition: attachment;filename=\"$fichier\"" );
header("Pragma: no-cache");
header("Expires: 0");
$fp= fopen('php://output', 'w');
foreach ($output as $fields)
{
fputcsv($fp, $fields);
}
fclose($fp);
exit();
Tryed with array_map and many other functions with no success. I'm sure that it should be a simple question of charset encoding but it seems that content type UTF-8 is not working at all.

Excel data are strange when MySQL column data has breaklines

I exported MySQL columns data into an excel file through the download concept using the header mechanisms. The problem is that if a column having text as its datatype has data containing breaklines like enumeration then the csv file is strange : the enumerated data are placed into different lines in the excel file. So how to make the data placed inside one cell ?
Here is the code of the download :
function downloadFile($outPut, $fileName){
$filesize = strlen($outPut);
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-type: text/enriched");
header("Content-length: $filesize");
header("Content-disposition: attachement; filename=$fileName");
ob_clean();
flush();
print($outPut);
exit();
}
My first suggestion would be to ensure that each of the fields you are exporting are within double quotes if they are not already, this will save a lot of formatting issues e.g. with commas within a field etc. If you are still having problems I would suggest trying to replace the newline characters with something that you will interpret as a new line (or just as space). Try this in your sql (around the field that ,ay have newline characters:
REPLACE(your_column_name,'\n',' ')
A dirty method is to use a "\r\n" as the actual row ending in the CSV file; and a simple "\n" as the breakline within a cell, making sure that you quote any cell values that contain the breakline.
$fh = fopen('test.csv', 'w+');
fwrite($fh, "sep=\t" . "\r\n");
fwrite($fh, 'A' ."\t" . 'B' . "\t" . 'C' . "\r\n");
fwrite($fh, 'D' ."\t" . "\"E\nF\nG\"" . "\t" . 'H' . "\r\n");
fclose($fh);
This example uses a tab separator between cells; and shows a three-line value in cell B2
EDIT
Or using fputcsv()
$fh = fopen('test2.csv', 'w+');
fwrite($fh, "sep=\t" . PHP_EOL);
fputcsv($fh, array('A', 'B', 'C'), "\t");
fputcsv($fh, array('D', "E\nF\nG", 'H'), "\t");
fclose($fh);

Comma Separated File, appending encrypted charter instead of new line

I am creating a comma separated file, that appends encrypted character at the end of each line instead of starting the next line in a new line?
$inner_exported_header_array[] = 'ID';
$inner_exported_header_array[] = 'First Name';
$exported_customers_arr [] = $inner_exported_header_array;
foreach ($_list AS $row) {
$inner_exported_array = array();
$inner_exported_array[] = $row['id'];
$inner_exported_array[] = $row['v_first_name'];
$exported_customers_arr[] = $inner_exported_array;
}
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Description: File Transfer');
header("Content-Type: text/plain");
header("Content-Disposition: attachment; filename=test.txt");
header("Pragma: no-cache");
header("Expires: 0");
outputCSV($exported_customers_arr);
function outputCSV($data) {
$outstream = fopen("php://output", "w");
function __outputCSV(&$vals, $key, $filehandler) {
fputcsv($filehandler, $vals); // add parameters if you want
}
array_walk($data, "__outputCSV", $outstream);
fclose($outstream);
}
Output is showing:
"ID","First Name"[special character not copied here]1,Testname
But if would be:
"ID","First Name"
1,Testname
Any thought, that our new line should be in a new line rather than inserting special characters at end of line ans starting new line from where the first line ends?
Summary from the comments:
The easiest solution may be to simply read the file in and replace every "\n" with "\r\n". The consumer of the file expects different line endings.
What are these characters? Seems like they're coming from your database, somehow? These "special" characters seem to contain newline (i.e. \n), which messes up your output.
I suggest checking the value of the last character of your problematic field using PHP's ord() function:
http://php.net/manual/en/function.ord.php
You could clean your CSV output using PHP's trim() function:
http://php.net/manual/en/function.trim.php
trim() also clears newline, which should solve your issue, if applied to the output of each field, i.e change this:
$inner_exported_array[] = $row['v_first_name'];
to:
$inner_exported_array[] = trim($row['v_first_name']);

Issue with control chars - PHP does not print \t (tab character)

i'm sending an XLS file with the header. Everything is working fine. But when i tell it to print the tab to separate the cells in the XLS by print \t. It does not prints the tab. It just prints the '\t' in the file and when i download the XLS file everything that should be in different cell is all in one cell with text like:
val1\tval2\tval3\t
Those three values should be separate in their separate cells.
i have been trying for 2 hours now nothing is working :(.
i send headers like this:
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$filename.$fileextention);
header("Pragma: no-cache");
header("Expires: 0");
and just print the values like
echo $val1 . '\t' . $val2 . '\t' . $val3;
i have tried using single or double quts. and print and echo both buy still :(
Try this (see quotes)
header('Content-type: application/vnd.ms-excel');
echo "val1\tval2\tval3";
I'm quite sure that quotes cause the issue.
echo $val1 . "\t" . $val2 . "\t" . $val3;
should do the thing. Just look at this:
<?php
echo 'Test\tTest';
echo "\r\n";
echo "Test\tTest";
echo "\r\n";
which outputs:
Test\tTest
Test Test
Use double quotes when you need control chars.
Hopefully this can solve your problem.
Use double quotes: "\t". Within single quotes only \\ and \' is recognised.
This should work:
echo $val1 . "\t" . $val2 . "\t" . $val3;
If it doesn't, it's a bug in PHP.

Categories