I am trying to put a column with a number with leading zeros into a csv file, but it keeps truncating the leading zeros, what can I do to keep them?
Here is the code I am using:
// fopen() here
function clean_zip($string){
if(preg_match("/^\d{5,}/", $string)){
$string = str_pad($string, 5, "0", STR_PAD_LEFT);
}
return $string;
}
while(($csv = fgetcsv($rhandle)) !== false){
// other rows here
$fcsv[9] = (string)clean_zip($csv[9]);
fputcsv($whandle, $fcsv);
}
As already pointed out in the comments, wrapping a number with double quotes (") will result in something like "0123".
The way to go is adding a leading single quote (') as written down in the documentation:
If you decide to enter a number directly as text, enter an apostrophe
(') first. For example, for years in column headings, you can enter
'1999, '2000 and '2001. The apostrophe is not visible in the cell, it
only indicates that the entry is to be recognized as a text. This is
useful if, for example, you enter a telephone number or postal code
that begins with a zero (0), because a zero (0) at the start of a
sequence of digits is removed in normal number formats.
Source: Formatting Numbers as Text
The data is now parsed as a string, which results in it being ignored in a function.
Another way is to format the column as a text column.
I just needed to tell Libre Office to display the column as a Text column instead of What ever it thought would be best for the column/cell.
Wrap with double quote characters ("). This is easy enough if you're sure there are only numbers -- if there's a possibility of having quotes in the string you'll have to be more careful.
Related
floatval('19500.00');
returns 19500 ;
however
echo floatval('19,500.00');
returns 19 ;
this could've really given me a big problem it was good that I've noticed :D ... is there some reason for that behavior or it's just a bug ... should all values be number_formatted before ouput?
You put that value in single quotes, so it's not treated as a numerical value, but as a string.
Here's php.net's explanation what happens to strings with floatval (from http://php.net/manual/en/function.floatval.php):
Strings will most likely return 0 although this depends on the
leftmost characters of the string.
Meaning: The leftmost characters of the string in your case is 19 - that's a numerical value again, so the output is 19.
Decimal and thousands separator symbols are defined by current locale used in your script.
You can set default_locale in php.ini globally, or change locale in your script on the go: http://php.net/manual/en/function.setlocale.php
Different locales have different separators. To check, which is the current separator symbol, you can use localeconv function: http://us2.php.net/manual/en/function.localeconv.php
$test = localeconv();
echo $test['decimal_point'];
#.
echo $test['thousands_sep'];
#,
But actually no one can make this function work properly with all these commas and dots, so the only solution is to clean the input removing everything except "." and numbers by regexp or str_replace:
echo floatval(preg_replace("/[^0-9\.]/", "", '19,500.00'));
#19500
echo floatval(str_replace(",", "", '19,500.00'));
#19500
I am stuck with the issue as currently the result is quite unexpected. I am calculating a hashed keyword length and it is surely giving me an unexpected result.
echo strlen("$2a$08$MphfRBNtQMLuNro5HOtw3Ovu20cLgC0VKjt6w7zrKXfj1bv8tNnNa");
Output - 6
Let me know the reason for this and why it is outputting 6 as a result.
Codepad Link - http://codepad.org/pLARBx6F
You must use single quotes '. With the double quotes ("), due to the $ in your string, parts of it get interpreted as variables.
Generally, it's not a bad idea to get accustomed to using single quotes unless you specifically need doubles.
Look at the "variables" contained here. They would be $2a, $08, and $MphfRBNtQM......
The first two couldn't be variables as they start with a number, thus, the 6 characters. The third one indeed could be a proper variable, but since it isn't set, it's empty.
Use the below code to calculate the string length -
echo strlen('$2a$08$MphfRBNtQMLuNro5HOtw3Ovu20cLgC0VKjt6w7zrKXfj1bv8tNnNa');
You need to use single quotes, as at the third occurrence of the symbol $, a alphabet is starting after it and it get treated as a new variable. So before this third occurrence of $ only 6 character were there and you were getting string length as 6
Try following
<?php
echo strlen('$2a$08$MphfRBNtQMLuNro5HOtw3Ovu20cLgC0VKjt6w7zrKXfj1bv8tNnNa');
?>
If you change your string and remove rest of '$' signs except the first one, then this will work fine because by adding $ it gets a special meaning in PHP.
Regarding to fgetcsv() documentation, there are some parameteres inside fgetcsv() function: Handle, length, delimiter, enclosure, and escape.
Now, I have 2 questions:
What does enclosure do exactly?
I have a csv file with 5 columns per line. Imagine it something like this: 1,2,3,4,5
So indexes are from 0 to 4. But whenever I want to get date from index 4, an empty value returns. Unless I put a comma after it (by filling an extra column after it that makes the contents like this: 1,2,3,4,5,6 ). How can I solve this issue ? It seems that there is some problem because of missing comma after the last item in each row of csv file!
1. The enclosure parameter is the character the encapsulates the data for a specific field, or "index". By default, the parameter is a ", which means that you can "enclose" strings in " characters.
Example:
1,2,"this is three",4
2. Per a comment, you're calling fgetcsv($handle, 10000, ','). It's possible, maybe, that the line(s) you're reading are longer than 10000 characters. Try changing the length to 0, which will be "no limit" and see if that helps. Another solution would be to try wrapping the column's value in double-quotes.
Enclosure is the character enclosing the field. It is an extra delimiter, of a sort.
For example hello,world has a comma as field delimiter, and has no text delimiter, while "hello","world" has a quote sign as text delimiter. Some systems employ delimited and undelimited values to indicate text and numeric fields, respectively (I believe Microsoft Excel does). This allows a field to contain the field delimiter in its value:
"Hello,world","Second Field","Third, and last, field".
Some other systems only enclose values containing the field delimiter, or values containing whitespace, which means that on those systems an undelimited value is not necessarily numeric.
If you have a "trivial" case - undelimited values, without escaped field-delimiters inside values (i.e., no 'A,firstpartB\,secondpartB,C' stuff) - you might skip CSV conversion altogether and run
$line = fgets($file, MAX_EXPECTED_LINE_LEN);
// This splits ' A, B, C ' into 'A', ' B' and ' C' (note spaces)
$row = explode(',', trim($line)); // other delimiters can be used
or
// Consider " , ", "," and ", " as the same delimiter
// i.e. ' Alpha , Beta , Gamma ' gets split into 'Alpha', 'Beta' and 'Gamma'
$row = preg_split('#\\s*,\\s*#', trim($line));
I cannot seem to reproduce the problem you are experiencing; could it be related to a different encoding of line endings (i.e., CRLF instead of LF)?
In a pinch, you can divide fgetcsv in the two components fgets and str_getcsv(), manipulating the line between the calls (with trim, or if the worse comes to the worst, by appending the missing comma).
It works to me on this way:
while ($row = $stmt -> fecht()){
echo "\"";
echo $row['email'];
echo "\"";
// Export every row to a file
$arr = array(',');
fputcsv($data, $arr, ";", '"' );
}
Could anyone tell me how to insert a space in between characters in a string using PHP, depending on the length for a UK post code?
e.g. if the string is 5 charterers, insert a space after the second character? If it is 6 characters insert after the third etc?
Use regex:
$formatted = preg_replace('/([a-Z0-9]{3})$/', ' \1', $postalCode);
Note that this only works on alphanumeric characters, but I'm assuming that's what the scope of the input should be.
I'm reading a .csv file (I have no control of the format of the file) and I'm trying to keep the leading zeros for the data in the resulting array. For instance, the .csv file has "0615" in a field, but resulting array contains "615". There are also fields in the .csv file that do not contain leading zeros, so adding zeros to the beginning of each field will not work.
I've tried to force functions to read the fields as a string, but explode, str_getcsv, fgetcsv all parse it as an integer and remove the leading zero beforehand. Any thoughts?
Edit: explode does NOT remove the leading zeros. Using explode with fgets works.
explode() works on a string basis; your type conversion must be happening elsewhere:
$data = "00555,00666,00777,00888";
$a = explode(",",$data);
foreach($a as $b) echo $b . " "; // 00555 00666 00777 00888
Use (string)$b if PHP insists on interpreting the strings as integers.
If you need the leading zeroes for presentation or uniform formatting processes then it might be easier to simply pad the numbers when you output them.
http://php.net/manual/en/function.str-pad.php should be of help here.
Use str_pad to add the leading zeros to the parsed integer, wherever you need it.
Or use sprintf, if you are familiar with it.
$num = 1;
$num = sprintf('%04d', $num);
// ^^
// ||_ How many leading digits?
// |_ Leading digit?
// output: 0001