Split text file aftering finding a match - php

I am trying to search for a string match then split the file contents. After some trial and error, I am hoping someone can provide a helping hand. After fgetcsv, searching a string becomes almost pointless. Ideally, I would like to find each occurrence of "appointment", and split the contents with a comma.
if (($handle = fopen('file.csv', "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if(preg_match('/appointments/', $data, $matches, 0))
{
$split = preg_split("/,/", $data);
print_r($split);
}
}
fclose($handle);
}
The print statements gives back nothing.

What do you meant by splitting the content with a comma? Or do you want to add a comma after each "appointments"?
Instead of fgetcsv, use fread and replace "appointments" with "appointments, " using str_replace
$filename = 'file.csv';
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
$contents = str_replace('appointments', 'appointments, ', $contents);
echo $contents;

As noted, the file has ASCII characters which need cleaning before processing.
After getting the file and looping, strip the contents of ASCII character sets.
$stripAscii = preg_replace('/[^(\x20-\x7F)]*/','',$data);
$datePos = strpos($stripAscii,'Appointment:');
$data = substr($data, $datePos);
$data = str_replace('Appointment:', ' ', $row2);
Now, all fields after "Appointment:" is returned.

Related

Getting unknown characters between each letter when reading uploaded CSV on Laravel

I'm trying to upload a CSV file, read its contents and import that data into a database, but apparently I'm getting some kind of bug where an unknown character shows between each character.
This is my code:
$file = $request->file('file');
$fileName = $file->getRealPath();
$file = fopen($fileName, "r");
$i = 0;
while (($column = fgetcsv($file, 10000, ";")) !== FALSE) {
if ($i == 0){
$i++;
continue;
}
echo print_r($column);$i++;
}
fclose($file);
This is what I get from print_r:
Any ideas on what could it be? I've tried opening the CSV with encoding UTF8 and UTF16 but I still have this issue.
Thanks in advance.
Most likely it's \0 char that some system appends. Check with ord($string[0])
You can simply do str_replace("\0", '', $string)
Or try some regex replace: preg_replace('/[^\w\d-.,\s]/', '', $string)

Converting TAB Delimited to CSV

I'm currently opening a TAB delimited file with the following code...
if (($handle = fopen($filetxt, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 0, "\t")) !== FALSE) {
// var_dump($data);
$num = count($data);
echo "<br>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
Now I'm just trying to figure out how I can put the data into a CSV using fputcsv. An example would be great -- right now I'm just trying to get the headers into a CSV and then I can go from there.
The data right now (that's being echoed) looked like this...
part_number
aaia_part_term_id
short_description
bullet_points
list_price
jobber_price
base_price
epc_code
length
width
height
weight
image_name
If I could just figure out how to echo only the header into the CSV, I think I can figure out the rest.
fopen only gives you a handle to the file. A csv file's formatting relies going through each line, the way you are reading the file uses all contents at once, try:
<?PHP
if($handle = fopen($filetext, "r") !== FALSE){
while (!feof($handle)) {
$line_of_text = fgets($handle);
foreach( fgetcsv($line_of_text, 0, "\t") as $csv_item)
print $csv_item."," ;
print "<br>";
}
fclose($handle);
}
?>
I haven't tested this
Since a CSV file is just a comma delimited data file, it might be simpler just to read the current tab-delimited file line by line, and replace tabs with commas
if (($handle = #fopen($filetxt, "r")) !== false) {
while (($line = fgets($handle, 0)) !== false) {
$csv_line = str_replace("\t", ",", $line);
// write $csv_line to your csv file
}
fclose($handle);
}

CSV import via PHP

I'm importing a .CSV into an application with the following:
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
It sort of works but it's far from perfect. I wanted to first get out the row heads and put them into an array and then loop round each row to get the data sets in.
It seems to be having delimitting problems as the first row (heads) are also including a few parts of the second row.
I exported the .csv file straight from Excel. Wonder if there are encoding tricks etc I might be missing.
It sounds like your 1000 limit is not long enough; you should set it to a high enough value for that file ... or set to 0 for unlimited (not recommended, because it tends to be slower).
Set it to 4096 or 8192 first and see how it goes.
// use 8kB buffer for reading comma delimited line
while (($data = fgetcsv($handle, 8192, ",")) !== FALSE) {
Update
Okay, on second thought, perhaps you should inspect the file and confirm a few things:
Are the delimiters really a comma? (I guess you've already established this)
Are the string enclosures always double quotes?
Are strings escaped with a backslash (default) or another double quote?
fgetcsv doesnt always properly detect line endings.
Try using before the fgetcsv call:
ini_set('auto_detect_line_endings', true);
I changed to 8192 and got same results
while (($data = fgetcsv($handle, 8192, ",")) !== FALSE) {
...
}
and then did this one and got same results
$handle = fopen($_FILES['filename']['tmp_name'], "r");
ini_set('auto_detect_line_endings', true);
while (($data = fgetcsv($handle, 8192, ",")) !== FALSE) {
$data = array_map('mysql_real_escape_string', $data);
Why are you not using file()?
$trimmed = file('somefile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

read and write file with newline php

I have a php file with the following info
One
Two
Three
Now i want to split them into an array, so i used:
$filehandle = fopen($filename, 'rb');
$line_of_text = fgets($filehandle);
$array = explode("\n", $line_of_text);
But it is not working.
They are written in the file like this:
$filehandle = fopen($textfile, 'a');
fputs($filehandle, $line . "\r\n");
fclose($filehandle);
So how do i read them into an array?.
Thanks.
I think you are looking for file(). However, it should be noted that this will leave all your array elements with a trailing CRLF sequence on them.
Alternatively (all these will strip the trailing CRLF):
$array = explode("\r\n", file_get_contents($filename));
...or...
$fp = fopen($filename, 'r');
$filecontents = fread($fp, filesize($filename));
$array = explode("\r\n", $filecontents);
...or...
$fp = fopen($filename, 'r');
$array = array();
while (($line = fgets($fp)) !== FALSE) $array[] = trim($line);
You should use the file function
file — Reads entire file into an array
$your_array = file ("filename", FILE_IGNORE_NEW_LINES); // add the flag to strip newlines

Use fgetcsv for tab delimited file

Is it possible to use fgetcsv in PHP to open a tab-delimited file?
$csvData = fgetcsv($fileHandle, 0, "\t");
Where $fileHandle is a valid file handle. The 0 is just to tell the function not to limit seeking through lines (however you can change this to suit, the docs do say not imposing a limit decreases performance).
Make sure to use double quotes around the "\t", single quotes will not work.
$fh = fopen($file, 'r');
while (($line = fgetcsv($fh, 0, "\t")) !== false) {
// do stuff
}
yes, you can specify tab "\t" in its parameters. see the doc.
while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE)

Categories