Writing to a CSV - column by column instead of row by row - php

I'm familiar with creating a CSV, then adding lines to it by using functions like fputcsv, or manually with fwrite. IE:
fwrite($fh, $facility . "\r\n");
fwrite($fh, $s . " - " . $e . "\r\n");
fwrite($fh, "\r\n");
fwrite($fh, "\r\n");
foreach ($first_column as $f){
fwrite($fh, $f . "," . "\r\n");
}
My $first_column array looks something like:
$first_column = array(
'Chocolate Milk',
'White Milk',
'Orange Juice',
'Apple Juice',
);
It creates a file that looks similar to this:
West Middle School
5/1/2013 - 5/3/2013
Chocolate Milk,
White Milk,
Orange Juice,
Apple Juice,
I'd like to add data in the next field based on dates. The data will look similar to this:
$second column['05/01/2013'] = array(5,3,2,2);
$third column['05/02/2013'] = array(5,1,3,5);
I then can just loop through each date, and match up the values to the $first_column mapping.
Can this be done? Or will I have to write the data on a row by row basis like:
$data_row['chocolate milk'] = array(5,5,3,6);
$data_row['white milk'] = array(3,1,5,0);
My desired CSV would be something like this:
West Middle School
5/1/2013 - 5/3/2013
,5/1/2013,5/2/2013
Chocolate Milk,5,5
White Milk,3,1
Orange Juice,2,3
Apple Juice,2,5

You can have data in your program in column basis. But write them to file in this manner is not optimal. Better will be to create csv structure in memory and then store it in row order.
However, you can store them in col-by-col. Just write first collumn. Close file. Reopen file, load it line-by-line and append to end of each line second column. This create you new "line". Write it to new file.... and repeat this until done. This is fastest solution to programm, if you want to col-by-col aproach. Efficiency of this approach will be poor, of course.

Related

Removing A Specific Line From A File

I have a text file like this:
1
2
3
4
5
6
7
8
9
10
And I want to remove specific lines which numbers are in an array like this:
$myfile='txt.txt';
$remove=array(1,3,6,7,10);
//wanna remove these lines
So I tried this code but It didn't work and It just doubles the text and ruins everything:
<?php
$myfile='txt.txt';
$remove=array(1,3,5,7,10);
$lines=file($myfile);
$countline=sizeof($lines);
$data=file_get_contents($myfile);
for ($i=0; $i < $countline+1; $i++) {
if (in_array($i, $remove)) {
$editeddata=str_replace($lines[$i], "", $data);
$removeline = file_put_contents($myfile, $editeddata.PHP_EOL , FILE_APPEND | LOCK_EX);
}
}
?>
I couldn't use ((for)) properly and I think it will just ruin the text because it deletes lines one after another have been deleted and it changes the order so I should have a code to remove them all at once.
And please don't give a code to just replace numbers because the main text file is not only numbers and contains word,etc...
Thanks A lot!
You're reading the file twice (with file and file_get_contents), which I think is confusing the later code. You have everything you need with the first call - an array of all the lines in the file. You're also using str_replace to remove the content, which seems a bit dangerous if any of the content is repeated.
I'd refactor this to simply filter the array of lines based on their line-number, then write it back to the file in a single operation:
$myfile = 'txt.txt';
$remove = [1, 3, 5, 7, 10];
// Read file into memory
$lines = file($myfile);
// Filter lines based on line number (+1 because the array is zero-indexed)
$lines = array_filter($lines, function($lineNumber) use ($remove) {
return !in_array($lineNumber + 1, $remove);
}, ARRAY_FILTER_USE_KEY);
// Re-assemble the output (the lines already have a line-break at the end)
$output = implode('', $lines);
// Write back to file
file_put_contents($myfile, $output);
If the file fits in memory then you can do the simple:
$myfile='txt.txt';
$remove=array(1,3,6,7,10);
file_put_contents($myfile, implode(PHP_EOL,array_diff($file($myfile,FILE_IGNORE_NEW_LINES), $remove)));
Note: Because it's a bit ambiguous whether $remove has the content or the lines you want to remove, the above code removes the content . If you want to remove lines change array_diff($file($myfile,FILE_IGNORE_NEW_LINES), $remove) to array_diff_keys($file($myfile,FILE_IGNORE_NEW_LINES), array_flip($remove))
If your file is large then you need to resort to some sort of streaming. I suggest against reading and writing to the same file and doing something like:
$myfile='txt.txt';
$remove=array(1,3,6,7,10);
$h = fopen($myfile,"r");
$tmp = fopen($myfile.".tmp", "w");
while (($line = fgets($h)) !== false) {
if (!in_array(rtrim($line, PHP_EOL), $remove)) {
fwrite($tmp, $line);
}
}
fclose($h);
fclose($tmp);
unlink($myfile);
rename($myfile.".tmp", $myfile);

Auto cut on thermal printer (php)

How can i perform auto cut on Epson TMT82 from PHP File? bellow is my config file.
Config:
$tmpdir = sys_get_temp_dir();
$file = tempnam($tmpdir, 'ctk');
$handle = fopen($file, 'w');
$condensed = Chr(27) . Chr(33) . Chr(4);
$bold1 = Chr(27) . Chr(69);
$bold0 = Chr(27) . Chr(70);
$initialized = chr(27) . chr(64);
$condensed1 = chr(15);
$condensed0 = chr(18);
$Data = $initialized;
$Data .= $condensed1;
Printing:
fwrite($handle, $Data);
fclose($handle);
copy($file, "//localhost/printer"); # printing
unlink($file)
Try to write chr(29) + 'V' (or chr(86)), and then the values for m and n, depending on the exact function you want to use as per the manual below (if you just want to cut without feeding at all, you want to use function A, which means you can just follow with a 0 (or 48, not sure why they mentioned both numbers in the manual...!?), like so:
chr(29) . "V" . 0
https://reference.epson-biz.com/modules/ref_escpos/index.php?content_id=87
(you need to be logged on to read this reference, but registering is free)
Edited: the chr() code for 'V' is 86, not 56
Edit2: Just to comment on what Matt Gibson said; chr(27) . chr(105) should also work on your model (just checked, also chr(27) . chr(109)), but it's an obsolete command, you should be using chr(29) . "V". In any case, some printers like to receive these sorts of commands on their own instead of having them along with the rest of the string.
Once you get this right, you should probably define a variable with the type of cut that you want. Ex. $cutPaper = chr(29) . "V" . 0;

Modify content of file in php

This file stores the number of item ordered to date. Therefore, I will need to read from the file for current number ordered and add it to the current quantity ordered and write it back.
I am new to PHP, so I am not sure what is the best approach here.
The format of the file is as follows:
$filename = "ordersToDate.txt";
if (!file_exists($filename))
{
$file = fopen($filename, "w");
$toWrite = "Total quantity ordered to date
\r\nTotal number of apples: ".$appleQty.
"\r\nTotal number of oranges: ".$orangeQty.
"\r\nTotal number of bananas: ".$bananaQty;
fwrite($file, $toWrite);
fclose($file);
}
else
{
// read individual item QTY ordered to date, add it with current ordered QTY and write back
}
If the file already exists, I need to read the QTY from it and update it. Is there a quick and easy way to get it (i.e., current QTY to date), provided that I know the string before it?
When you open a file like that you can specify "or die" like this:
$filename = fopen("ordersToDate.txt", "w") or die ("Can't open file.");
Then you can write to the file like you're doing and then close it. If the file exists already it will just open the existing one. If it doesn't exist PHP will create the file.
<?php
// can add another one for 'bananas: ' etc.
$re = "/(?!apples: )(\\d)/"; // for apples
// $str = file_get_contents($filename);
$str = "Total quantity ordered to date\r\nTotal number of apples: 3\r\nTotal number of oranges: 4\r\nTotal number of bananas: 3";
$subst = "5"; // $subst = $new_number;
// replace the number after 'apples: ' with whatever you want
$result = preg_replace($re, $subst, $str, 1);
echo var_dump($result);
// file contents, with apple number replaced with 5 (from 3) can now be written to file
?>

How to split content into equal parts then write to file in PHP

I have been reading/testing examples since last night, but the cows never came home.
I have a file with (for example) approx. 1000 characters in one line and want to split it into 10 equal parts then write back to the file.
Goal:
1. Open the file in question and read its content
2. Count up to 100 characters for example, then put a line break
3. Count 100 again and another line break, and so on till it's done.
4. Write/overwrite the file with the new split content
For example:
I want to turn this => KNMT2zSOMs4j4vXsBlb7uCjrGxgXpr
Into this:
KNMT2zSOMs
4j4vXsBlb7
uCjrGxgXpr
This is what I have so far:
<?php
$MyString = fopen('file.txt', "r");
$MyNewString;
$n = 100; // How many you want before seperation
$MyNewString = substr($MyString,0,$n);
$i = $n;
while ($i < strlen($MyString)) {
$MyNewString .= "\n"; // Seperator Character
$MyNewString .= substr($MyString,$i,$n);
$i = $i + $n;
}
file_put_contents($MyString, $MyNewString);
fclose($MyString);
?>
But that is not working quite the way I anticipated.
I realize that there are other similiar questions like mine, but they were not showing how to read a file, then write back to it.
<?php
$str = "aonoeincoieacaonoeincoieacaonoeincoieacaonoeincoieacaonoeincoieacaon";
$pieces = 10;
$ch = chunk_split($str, $pieces);
$piece = explode("\n", $ch);
foreach($piece as $line) {
// write to file
}
?>
http://php.net/manual/en/function.chunk-split.php
Hold on here. You're not giving a file name/path to file_put_contents();, you're giving a file handle.
Try this:
file_put_contents("newFileWithText.txt", $MyNewString);
You see, when doing $var=fopen();, you're giving $var a value of a handle, which is not meant to be used with file_put_contents(); as it doesnt ask for a handle, but a filename instead. So, it should be: file_put_contents("myfilenamehere.txt", "the data i want in my file here...");
Simple.
Take a look at the documentation for str_split. It will take a string and split it into chunks based on length, storing each chunk at a separate index in an array that it returns. You can then iterate over the array adding a line break after each index.

array_unique not working with filename strings imported from text file

THE PROCESS:
User checks checkboxes to share files with customer accounts
Checkbox values are compared against an array stored in a txt file from the customers folder
The arrays are compared by being merged into one array using array_merge()
The duplicates are eliminated using array_unique()
New array written to txt file
THE PROBLEM:
If my text file already contains the following data: (numbers representing text file lines)
M HTH A277 Frame Off STD Specs 02-01-12.pdf
M HTH A277 Frame On STD Specs 02-01-12.pdf
M HTH Option Can Price List 02-02-2012.xls
I then try to share more files including those that are already shared. My new text file looks like this: (numbers representing text file lines)
M HTH A277 Frame Off STD Specs 02-01-12.pdf
(blank)
M HTH A277 Frame On STD Specs 02-01-12.pdf
(blank)
M HTH Option Can Price List 02-02-2012.xls
(blank)
(blank)
M HTH A277 Frame Off STD Specs 02-01-12.pdf
M HTH A277 Frame On STD Specs 02-01-12.pdf
M HTH Option Can Price List 02-02-2012.xls
Valley Creek Estates - 2010.pdf
The values above are the exact values I'm dealing with. I've tried to be as thorough as possible with this explanation which could make things confusing. If anyone can provide me with any suggestions they would be greatly appreciated. Thanks in advance. This is what I've got for code so far:
THE CODE:
$arr = $_POST['checked'];
$cust = $_POST['custname'];
if ($cust != ""){
$myFile = "CONTA.txt";
//If file exists get previous array from file
if (file_exists("customer/" . $cust . "/" . $myFile)) {
$fh = fopen("customer/" . $cust . "/" . $myFile, 'r') or die("");
while (!feof($fh) ) {
$compare[] = fgets($fh);
}
fclose($fh);
//Combine checkbox array with previous array & eliminate duplicates
$combined = array_unique(array_merge($compare,$arr));
}
else
{
//Since no previous file or array existed. Just use current checkbox array.
$combined = $arr;
}
//Input array into file
$fh = fopen("customer/" . $cust . "/" . $myFile, 'w') or die("can't open file");
foreach ($combined as $value) {
fwrite($fh, $value . "\n");
}
echo "<span class='message'>Items shared successfully!</span>";
fclose($fh);
}
}
To me it looks like the problem is "\n" character. Each line has a new line on the end and when you compare one line that has the newline character and the same line that doesn't they aren't the same. I would confirm this by echoing each line from the fgets. If they are line broken, then you know you are getting the new line character.
EDIT:
I would try putting
trim(fgets($fh))
by default it should strip the newline character
trim specs

Categories