Wrap CSV values generated by PHP fputcsv() with " " - php

So, my code generates a CSV file using PHP's built-in fputcsv function.
For the delimiter, I use ',' (a comma).
For the enclosure, I use '"' (a double-quote).
However, when I try something like
fputcsv($file,array('a','b',"long string, with commas",NULL,''),',','"');
it outputs
a,b,"long string, with commas",,
but I would like it to output
"a","b","long string, with commas","",""
Is there an easy way to deal with this, or would I have to write a replacement for fputcsv?

This is not usually a problem for CSV files.
fputcsv puts quotes around the value if it would be ambiguous. For example,
a,b,"long string, with commas",,
is not ambiguous, but,
a,b,long string, with commas,,
is, and will in most (read: all) cases be interpreted by the CSV reader as having more than 5 fields.
CSV parsers will accept string literals even without quotes around them.
If you want quotes around the values anyway, the following snippet would do that. It doesn't escape quotes inside the string - that exercise is left to the reader:
$row = '"' . implode('", "', $rowitems) . '"';
You would want to put this in a loop for all your rows.

I worked around this by inserting some bogus string characters, with a space, ## ##, and then removing them. Here's a sample implementation:
//$exported is our array of data to export
$filename = 'myfile.csv';
$fp = fopen($filename, 'w');
foreach ($exported as $line => $row) {
if ($line > 0) {
foreach ($row as $key => $value) {
$row[$key] = $value."## ##";
}
}
fputcsv($fp, $row);
}
fclose($fp);
$contents = file_get_contents($filename);
$contents = str_replace("## ##", "", $contents);
file_put_contents($filename, $contents);
This encloses all fields in double quotes, including empty ones

I think solution will be like this,
$order_header_arr = array("Item1", "Item2","This is Item3");
fputcsv($fp, $order_header_arr,',',' ');
remember " "[Space] Between third parameter of fputcsv

Any reason you can't str_replace(',,',',"",',$output); ? You'd also have to see if the last or first character is a comma and if so, replace the comma with ,""

fputcsv will not enclose all array variables in quotes. Having a numeric array value without quotes may be correct but presents a problem when a label or address program encounters a numeric defined US zip code because it will strip the leading zeros when printing. Thus 05123-0019 becomes 5123-19.
To enclose all values, whether they exist or not, in quotes I read the input file with fgetsrc and write a corrected version using fwrite. fgetsrc reads the record into array variables. Since fwrite writes a variable, you must string the array variables, enclose them in quotes and separate the array variable with a comma. Then add the record separator.
<?php
// fgetcsv - read array with fgetcsv and string into output variable
// then write with fwrite
// $ar is the array populated from fgetcsv and $arc is the variable strung
// with array variables enclosed in quotes and written using fwrite.
$file_in = fopen("reinOCp.csv","r") or die("Unable to open input file
reinOCp.csv!");
$file_out = fopen("printLABEL.csv", "w") or die("Unable to open output file
prtLABEL!");
while (!feof($file_in)) { //loop through each record of the input file
$ar=fgetcsv($file_in); //read the record into array $ar
if (is_array($ar)){ //this loop will string all the array values plus
// the end of record into variable $arc and then write the variable
$arc = ""; //clear variable $arc
foreach ($ar as $value) {
$arc .= '"' . $value . '",'; // add the array values, enclose in
// quotes with comma separator and store in variable $arc
}
$arc .= "\n"; //add end of record to variable $arc
fwrite($file_out, $arc) or die ("ERROR: Cannot write the file");
//write the record using variable $arc
}
}
echo "end of job";
fclose($file_in);
fclose($file_out);
?>

Related

How to find particular pattern using regex?

I have some .php files in a directory that calls a user defined function:
_l($string);
each time different string is passed to that function and all strings are static, (i.e. not a single string is entered by user input).
Now I want a script that can list down all the strings form all the files of that directory, which are passed into _l($string);
I had tried:
$fp = fopen($file, "r");
while(!feof($fp)) {
$content .= fgets($fp, filesize($file));
if(preg_match_all('/(_l\(\'.*?\'\);)/', fgets($fp, filesize($file)), $matches)){
foreach ($matches as $key => $value) {
array_push($text, $value[0]);
}
}
}
I get strings but not every strings those are in files, some strings are not match with given regex, so what are the condiotion that is required to get all the strings?
This is easier to get strings in double " or single ' quotes as the _l() function argument.
$string = file_get_contents($file);
preg_match_all('/_l\([\'"](.*?)[\'"]\);/', $string, $matches);
$text = $matches[1];
If needed you can add some optional spaces before and after the ( and before the ):
'/_l\s*\(\s*[\'"](.*?)[\'"]\s*\);/'
Also, if the function can be used in a loop or if or something where it's not terminated by a semi-colon ; then remove it from the pattern.

PHP Split string with exception

I have a string that need to be split out :
3,1,'2015,05,14,11,18,0', 99
I want to split it into
3
1
'2015,05,14,11,18,0'
99
How could I do this with PHP ?
One of the comments (#tuananh in particular) said csv parser, so a little bit of trial, fgetcsv will work too, you'll just got to have that temporary file that holds the simple string, just unlink it after the operation.
Just set the enclosure to single quotes so that when the parser breaks it up, it gets the whole string enclosed with single quotes.
$string = "3,1,'2015,05,14,11,18,0', 99";
file_put_contents('temp.csv', $string); // create temporary file
$fh = fopen('temp.csv', 'r'); // open
$line = fgetcsv($fh, strlen($string) + 1, ',', "'"); // set enclosure to single quotes
fclose($fh);
unlink('temp.csv'); // remove temp file
print_r($line); // Array ( [0] => 3 [1] => 1 [2] => 2015,05,14,11,18,0 [3] => 99 )
// echo implode("\n", $line);
Sidenote: If this is indeed a csv file, then just use fgetcsv for the whole thing.
EDIT: As #deceze said about use the csv function for strings
There's this thing called str_getcsv, so no need to actually put it inside a file the unlink it whatsoever.
$string = "3,1,'2015,05,14,11,18,0', 99";
$line = str_getcsv($string, ',', "'"); // set enclosure to single quotes
print_r($line);

enclosure parameter in fputcsv not behaving as expected

This I believe has a simple explanation, I just cannot see it. I want to generate a pretty simple csv delimetered file with double quotes around field values.
As per the manual page on fputcsv(), I try to pass on the delimiter and enclosure argument explicitly to have double-quoted field values required for data import in third-party application as in function call below:
// relevant line of codes ...
while($row = mysql_fetch_array($result)){
$name_pieces = "";
$name_pieces = explode(" ", $row['name']);
$numberOfPieces = count($name_pieces);
$lastNameIndex = $numberOfPieces - 1;
$lastname = $name_pieces[$lastNameIndex];
$firstname = $name_pieces[0];
} // Line array becomes the first, second, third fields in resulting .csv output.
$line = array( $row['username'],
$row['name'],
$firstname,
$lastname,
$row['description'] );
$data[] = $line;
}
foreach($data as $dataLine){
if(fputcsv($fh, $dataLine, ',', '"') === false){
die("Unable to write to csv file.");
}
}
Following is a sample of the script's .csv output, notice that only second and last fields are quoted.
AG,"Alan Gaulois",Alan,Gaulois,"(AG) Alan Gaulois"
COMMIS,commis,commis,commis,"(COMMIS) commis"
DU,"Denis Fargo",Denis,Fargo,"(DF) Denis Fargo"
Anyone have an idea why the fields are not all quoted? I could well have missed something on doc page, any insight appreciated!
To my knowledge, yes, delimiters are only needed if there are spaces, if you need something else, consider using array_map.
Something like:
function surroundWithQuotes ($input)
{
$input = str_replace('"', '""', $input); //escaping in csv files is done by doing the same quote twice, odd
return '"' . $input . '"';
}
foreach($data as $dataLine){
if(fputcsv($fh, array_map("surroundWithQuotes" $dataLine),$dataLine, ',', '') === false){
die("Unable to write to csv file.");
}
}
the function just sets quotes, if necessary. If there is no space, special char or quote inside the string you want to write, no enclosing quotes are needed.
The $enclosure argument doesn't tell the parser "you have to quote everything", but it tells the parser, which char to use to quote (by default it is ", so you don't have to write it).
There's something missing in the above mentioned answers, the predicate or call back function would return "" in case of an empty string.
Ideally it should be.
function encloseWithQuotes($value)
{
if (empty($value)) {
return "";
}
$value = str_replace('"', '""', $value);
return '"'.$value.'"';
}

str_getcsv example

I want to parse a comma separated value string into an array. I want to try the str_getcsv() php function but I can't find any good examples on how to use it.
For example I have an input where users submit tags for programming languages (php, js, jquery, etc), like the "tags" input in stackoverflow when you submit a question.
How would I turn an input with example value="php, js, jquery" into an array using str_getcsv?
Its true that the spec at http://us3.php.net/manual/en/function.str-getcsv.php doesn't include a standard example, but the user-submitted notes do a decent job of covering it. If this is a form input:
$val = $_POST['value'];
$data = str_getcsv($val);
$data is now an array with the values. Try it and see if you have any other issues.
I think you should maybe look at explode for this task.
$values = "php, js, jquery";
$items = explode(",", $values);
// Would give you an array:
echo $items[0]; // would be php
echo $items[1]; // would be js
echo $items[2]; // would be jquery
This would probably more efficient than str_getcsv();
Note that you would need to use trim() to remove possible whitespace befores and after item values.
UPDATE:
I hadn't seen str_getcsv before, but read this quote on the manpage that would make it seem a worthwhile candidate:
Why not use explode() instead of str_getcsv() to parse rows?
Because explode() would not treat possible enclosured parts of
string or escaped characters correctly.
For simplicity and readability, I typically find myself using just explode(), only adding in str_getcsv() if the following two conditions are met: 1) the primary delimiter is also used within the data itself; 2) the token that I'm trying to use as the main delimiter is enclosed by another distinct character.
For example, a basic parser for a CSV file:
$filename = $argv[1];
if (empty($filename)) { echo "Input file required\n"; exit; }
$AccountsArray = explode("\n", file_get_contents($filename));
As long as each of the elements of $AccountsArray doesn't embed a "," within the data itself, this will work perfectly and is straightforward and easy to follow:
foreach ($AccountsArray as $entry) {
$acctArr = explode(",", $entry);
}
However, often the data will contain the delimiter, at which point an enclosing token (a " in this example) has to be present. If so, then I switch to str_getcsv() like so:
foreach ($AccountsArray as $entry) {
$acctArr = str_getcsv($entry, ",", "\"");
}
//get the csv
$csvFile = file_get_contents('test.csv');
//separate each line
$csv = explode("\n",$csvFile);
foreach ($csv as $csvLine) {
//separet each fields
$linkToInsert = explode(",",$csvLine);
//echo what you need
//$linkToInsert[0] would be the first field, $linkToInsert[1] second field, etc
echo '• ' . $linkToInsert[1] . '<br>';
}
The code is quite simple, using the Str_getcsv function, we will go
through each line of the CSV file "images.csv" that is located in the
same directory as our script.
NOTE: Functions used are compatible with versions of PHP >= 5.3.0
//First, reading the CSV file
$csvFile = file('file.csv');
foreach ($csvFile as $line) {
$url = str_getcsv($line);
$ch = curl_init($url[0]);
$name = basename($url[0]);
if (!file_exists('directory/' . $name)) {
$fp = fopen('directory/' . $name, 'wb');
}
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
}

php fputcsv and enclosing fields

I was just about to ask the same questions as the question aksed here.... Forcing fputcsv to Use Enclosure For *all* Fields
The question was
When I use fputcsv to write out a line
to an open file handle, PHP will add
an enclosing character to any column
that it believes needs it, but will
leave other columns without the
enclosures.
For example, you might end up with a
line like this
11,"Bob ",Jenkins,"200 main st. USA
",etc
Short of appending a bogus space to
the end of every field, is there any
way to force fputcsv to always enclose
columns with the enclosure (defaults
to a ") character?
The answer was:
No, fputcsv() only encloses the field
under the following conditions
/* enclose a field that contains a delimiter, an enclosure character, or a newline */
if (FPUTCSV_FLD_CHK(delimiter) ||
FPUTCSV_FLD_CHK(enclosure) ||
FPUTCSV_FLD_CHK(escape_char) ||
FPUTCSV_FLD_CHK('\n') ||
FPUTCSV_FLD_CHK('\r') ||
FPUTCSV_FLD_CHK('\t') ||
FPUTCSV_FLD_CHK(' ')
)
There is no "always enclose" option.
I need to create a CSV file will every field enclosed... What would be the best solution?
Thanks in advance...
Roll your own function - its not hard:
function dumbcsv($file_handle, $data_array, $enclosure, $field_sep, $record_sep)
{
dumbescape(false, $enclosure);
$data_array=array_map('dumbescape',$data_array);
return fputs($file_handle,
$enclosure
. implode($enclosure . $field_sep . $enclosure, $data_array)
. $enclosure . $record_sep);
}
function dumbescape($in, $enclosure=false)
{
static $enc;
if ($enclosure===false) {
return str_replace($enc, '\\' . $enc, $in);
}
$enc=$enclosure;
}
(above is using unix style escaping)
C.
A workaround: Supposing you have your data in a 2-dimensional array, you can append a string that will force quoting and you are sure is not contained in your data ("## ##" here) and then remove it:
$fp = fopen($filename, 'w');
foreach ($data as $line => $row) {
foreach ($row as $key => $value) {
$row[$key] = $value."## ##";
}
fputcsv($fp, $row);
}
fclose($fp);
$contents = file_get_contents($filename);
$contents = str_replace("## ##", "", $contents);
file_put_contents($filename, $contents);
I have encountered the same problem, and I have solved it as follows.
I have inserted single quotes to each array value.
This way when you open the csv file with excel, the scientific notation E + 15 will no longer be displayed.
Here I share you as I did.
This worked for me, I hope you do too.
Regards
// this function add a single quote for each member of array
function insertquote($value) {
return "'$value'";
}
# here i send each value of array
# to a insertquote function, and returns an array with new values,
# with the single quote.
foreach ($list as $ferow) {
fputcsv($fp, array_map(insertquote, $ferrow), ';');
}

Categories