$file = new SplFileObject('D:\BackUp\addressbook.csv');
print_r($file->getCsvControl());
What i am trying to do is find the delimiter of a csv file using php. the addressbook.csv file looks like
"id";"firstname";"lastname";"phone";"email"
"1";"jishan";"ishrak";"17878";"jishan.ishrak#gmail.com"
and another file is addressbook1.csv which is like
"id","firstname","lastname","phone","email"
"1","jishan","ishrak","17878","jishan.ishrak#gmail.com"
one is separated by "," and another one is with ";" but the function
getCsvControl()
always returns an array like
Array ( [0] => , [1] => " )
I mean in the [0] index it always gives "," for both files
is there a way to solve this issue.
This is not a bug. SplFileObject::getCsvControl() is never intended to detect the delimiter from a CSV file. It returns only the default control characters or the one previously set with SplFileObject::setCsvControl(). And this set CSV control characters are used, if is nothing handed over in the SplFileObject::fgetcsv() method.
Ok, it's badly documented, but this were my first thoughts, the method would never detect the characters and a look into the php source code confirmed this.
Proabably this is a bug?
as you can see here php doc 1st comment 1 year ago - Seems that this function always returns the same delimiter.
UPDATE
this is not a bug look at Pazi ツ answer.
Related
I apologize if this question has a no brainer answer. I am still learning more ins and outs of php.
I have a snippet of code that is taking in a CSV file. This CSV file is uploaded by a user who downloads it from an external source. In the CSV file, the person's first name and last name is not split in separate columns. Therefore, in PHP the following is used:
$member_name = explode( " ", $application_data[5]);
The problem is that when this data is then used to render a PDF document to send a letter to the member, it cuts off their last name if their last name is two words.
The information is loaded into the PDF document with the first name and last name field by using:
$member_name[0],
$member_name[1]
Can I safely do:
$member_name[0],
$member_name[1] + $member_name[2]
Even if 99% of the members do not have a space in the last name? Will I get an error that member_name[2] doesn't exist 99% of the time this is done?
I've done some searching on array_merge. Is that a better option? I've been trying to search for how php handles when you add something that doesn't exist and I'm drawing a blank.
I don't want to assume my solution will work and then when the person uploads their CSV file tomorrow, they get an error.
Or maybe I'm looking at this the wrong way and before it attempts to render a pdf document, I should do an if statement that figures out if $member_name[2] exists.
Thank you!
You can use the limit parameter of explode to only split at the first space.
$member_name = explode( " ", $application_data[5], 2);
Of course, if the first name also has more than one word, this still won't be quite right. Names are tricky.
Regarding array_merge, I don't think it would really be useful in this situation.
You could just use a limiter on your explode to only seperate on the first space. Here is an example.
$name = "George The King";
print_r(explode(' ', $name, 2)); //prints -> Array ( [0] => George [1] => The King )
OK, so I shave my head, but if I had hair I wouldn't need a razor because I'd have torn it all out tonight. It's gone 3am and what looked like a simple solution at 00:30 has become far from it.
Please see the code extract below..
$psusername = substr($list[$count],16);
if ($psusername == $psu_value){
$answer = "YES";
}
else {
$answer = "NO";
}
$psusername holds the value "normann" which is taken from a URL in a text based file (url.db)
$psu_value also holds the value "normann" which is retrieved from a cookie set on the user's computer (or a parameter in the browser address bar - URL).
However, and I'm sure you can guess my problem, the variable $answer contains "NO" from the test above.
All the PHP I know I've picked up from Google searches and you guys here, so I'm no expert, which is perhaps evident.
Maybe this is a schoolboy error, but I cannot figure out what I'm doing wrong. My assumption is that the data types differ. Ultimately, I want to compare the two variables and have a TRUE result when they contain the same information (i.e normann = normann).
So if you very clever fellows can point out why two variables echo what appears to be the same information but are in fact different, it'd be a very useful lesson for me and make my users very happy.
Do they echo the same thing when you do:
echo gettype($psusername) . '\n' . gettype($psu_value);
Since i can't see what data is stored in the array $list (and the index $count), I cannot suggest a full solution to yuor problem.
But i can suggest you to insert this code right before the if statement:
var_dump($psusername);
var_dump($psu_value);
and see why the two variables are not identical.
The var_dump function will output the content stored in the variable and the type (string, integer, array ec..), so you will figure out why the if statement is returning false
Since it looks like you have non-printable characters in your string, you can strip them out before the comparison. This will remove whatever is not printable in your character set:
$psusername = preg_replace("/[[:^print:]]/", "", $psusername);
0D 0A is a new line. The first is the carriage return (CR) character and the second is the new line (NL) character. They are also known as \r and \n.
You can just trim it off using trim().
$psusername = trim($psusername);
Or if it only occurs at the end of the string then rtrim() would do the job:
$psusername = rtrim($psusername);
If you are getting the values from the file using file() then you can pass FILE_IGNORE_NEW_LINES as the second argument, and that will remove the new line:
$contents = file('url.db', FILE_IGNORE_NEW_LINES);
I just want to thank all who responded. I realised after viewing my logfile the outputs in HEX format that it was the carriage return values causing the variables to mismatch and a I mentioned was able to resolve (trim) with the following code..
$psusername = preg_replace("/[^[:alnum:]]/u", '', $psusername);
I also know that the system within which the profiles and usernames are created allow both upper and lower case values to match, so I took the precaution of building that functionality into my code as an added measure of completeness.
And I'm happy to say, the code functions perfectly now.
Once again, thanks for your responses and suggestions.
I am trying to assign a variable in watir method after reading the text file. I am using the following method. In loop, first loop is working fine but in second loop it shows error.
My code is as follows:
file = File.new("states.txt", "r")
contentsArray=[] # start with an empty array
file.each_line {|line|
contentsArray.push line
}
browser = Watir::Browser.new
browser.goto 'http://example.com'
for y in 0..2 do
puts state=contentsArray[y]
browser.text_field(:name => 'Keyword').set 'Pediatrics'
browser.text_field(:name => 'Address').set "#{state}"
browser.div(:id => 'uniform-formSearchDoctorBtn').fire_event :click
browser.link(:class => "start-over pull-right gen-button").click
end
following error occurred .
`assert_exists': unable to locate element, using {:id=>"uniform-formSearchDoctorBtn", :tag_name=>"div"} (Watir::Exception::UnknownObjectException)
Where as when I am putting an static array in place of contentsArray
contentsArray=Array['AL','AK','AZ','AR']
Then code works fine.
Yes Got the solution with the help of justin.
if you output the contentsArray, you will likely get
["AL\n", "AK\n", "AZ\n", "AR"]
Notice that there is a "\n", which is the line break character. You want to strip the line break by changing contentsArray.push line to
contentsArray.push line.strip
For more details, see the question How do I remove carriage returns with Ruby? – Justin Ko
I have the following named capture group that works exactly as intended. It grabs the last date/time of a specific format from a string of text.
$re = "/.*(?<date>[0-9]+\\/[0-9]+\\/[0-9]+ [0-9]+:[0-9]+:[0-9]{1,2} (AM|PM))/s";
I want to capture the user ID that follows so I changed it to the following
$re = "/.*(?<date>[0-9]+\\/[0-9]+\\/[0-9]+ [0-9]+:[0-9]+:[0-9]{1,2} (AM|PM)) (?<name>\\w+)/s";
However when I do so it breaks both values giving the following error
Notice: Undefined index: date in Q:\XAMPP\htdocs\index.php on line 272
The Error stems from the preg_match matches array being blank. Print_r confirms the array does not contain any information once the regex is changed to the second value.
Both of these work fine in external sites as the link below to Regex101 shows
http://regex101.com/r/zO0mK0/4
Using PHP 5.5.9
So the question is, am I missing something in this regex statement that is breaking it between the external site and my internal code or does this work meaning it is 100% purely my php that is causing this issue.
$LastDateRegex = "/.*(?<date>[0-9]+\\/[0-9]+\\/[0-9]+ [0-9]+:[0-9]+:[0-9]{1,2} (AM|PM))/s";
preg_match($LastDateRegex, $arr2['WorkLog'], $LastDateMatches);
$Modsecs = (strtotime($ts) - strtotime($LastDateMatches['date']))%60;
This is an example of the code being used. As mentioned above, I know the error stems from the $LastDateMatches array being empty for the second regex example, however the code works 100% with the first so there is something between the two that causes the issue.
You have an extra \ here: \\w+ and \\ at a few places, if that makes a difference?
Not quite sure what you want returned but runnning this regular expression, where $str is the text you have in your regex101-link,
$regex = "/.*(?<date>\d+\/\d+\/\d+ \d+:\d+:\d{1,2} (?:AM|PM)) (?<name>\w+)/s";
preg_match($regex, $str, $LastDateMatches);
Output,
Array
(
[0] => ...
[date] => 6/20/2014 10:04:32 PM
[1] => 6/20/2014 10:04:32 PM
[name] => ihugett
[2] => ihugett
)
I am getting a variable from a socket. After reading the respond I am trying to convert the value to a number. if I print the respond it looks correct however when I convert it to number using floor() it doesn't give me the right answer. I also tried to print the length of the variable and it is still not working as it suppose to: This one is for value :185
echo("**************** ".floor($res[0]));
echo "################### $res[0]";
echo "------------- ".strlen($res[0]);
output:
**************** 1################### 185------------- 12
I have also tried stripslashes, trim and also ereg_replace('[:cntrl:]', '',$res[0])
Please try the following: intval($res[0])
You can try also with:
$res = (int)$reg[0];
Hope this helps.
Bye
Ok I found the problem. I saved the value in a file and opened the file using notepad++. I saw the following character in between my string:
SOH,NULL, and bunch of other non character values
What I am assuming is PHP automatically ignore the ASCII values are not show able on the screen (less than 21Hex).