php wont write correctly to textfile - php

so i have the following code:
myarray[1] = item1, element1, element2
myarray[2] = item2, element1, element2
$outfile = "csv.txt";
$filewriter = fopen($outfile, "w"); // open for write
foreach($myarray as $item) {
fwrite($filewriter, $item);
}
which produces the following in the txt file:
item1,element1,element2item2,element1,element2
if i try to use "\n" it produces this output:
item1,element1,element2
(blank line)
item2,element1,element2
how do i get it too:
item1,element1,element2
item2,element1,element2
This is the \n
function writetofile($myarray){
$outfile = "csv.txt";
$filewriter = fopen($outfile,"w"); // open for write
$item=$myarray[0]."\n".$myarray[1];
fwrite($filewriter, $item);
Thanks

Try with the code below
<?php
$myarray[1] = 'item1, element1, element2';
$myarray[2] = 'item2, element1, element2';
$outfile = "csv.txt";
$filewriter = fopen($outfile, "w"); // open for write
foreach($myarray as $item) {
fwrite($filewriter, $item.'
');
}

Why not like this?
<?php
$myarray = array("item1 ,", "element1 ,", "element2 \r\n","item2 ,","element1 ,","element2");
$array_length = count($myarray); // Array length
$outfile = "csv.txt";
$filewriter = fopen($outfile, "w");
for($x=0;$x<$array_length;$x++)
{
echo $myarray[$x];
fwrite($filewriter, $myarray[$x]);
}
?>
The following code gives you (csv.txt) :
item1 ,element1 ,element2
item2 ,element1 ,element2

Related

php unable to open file when open and write into file

i try to read a text file line by line and if any line contain "/" then i need to write them into separate file.
example line
CA,T2B,Calgary (Forest Lawn / Dover / Erin Woods),Alberta,AB,Calgary,,,,51.0209,-113.981,6
i need to write this as 4 lines, like
CA,T2B,Calgary,Alberta,AB,Calgary,,,,51.0209,-113.981,6
CA,T2B, Forest Lawn ,Alberta,AB,Calgary,,,,51.0209,-113.981,6
CA,T2B, Dover,Alberta,AB,Calgary,,,,51.0209,-113.981,6
CA,T2B, Erin Woods,Alberta,AB,Calgary,,,,51.0209,-113.981,6
what i've tried so far is
$file = fopen("test.txt", "r");
while (!feof($file)) {
$my_string = fgets($file);
$special_chars = array("/");
if (array_intersect(str_split($my_string), $special_chars)) {
echo fgets($file) . "<br />";
$myfile = fopen("fileWithFL.txt", "w") or die("Unable to open file!");
fwrite($myfile, fgets($file));
fclose($myfile);
}else{
echo fgets($file) . "<br />";
$myfile = fopen("fileWithoutFL.txt", "w") or die("Unable to open file!");
fwrite($myfile, fgets($file));
fclose($myfile);
}
}
fclose($file);
[
file i get from "CA.zip"
how can i do this?
thank you!
You're repeatedly opening and closing fileWithFL.txt and fileWithoutFL.txt, which is inefficient. Better to just open them once before you loop through the input file.
You're also using fgets(), which makes it difficult to parse the input file. Since the input file seems to be in CSV format, you should use fgetcsv().
As for detecting rows that contain multiple cities, I'm looking for the presence of /, splitting on ( or /), removing any trailing ), and trimming the resulting name. That should give you all the cities in a neat array.
$file = fopen("test.txt", "r");
$file_with_fl = fopen("fileWithFL.txt", "w+");
$file_without_fl = fopen("fileWithoutFL.txt", "w+");
while ($a = fgetcsv($file)) {
if ( FALSE == strpos( $a[2], '/' ) ) {
fputcsv( $file_without_fl, $a );
} else {
$cities = preg_split( '/[\(\/]/', $a[2] ); // Split on '(' and '/'
foreach ( $cities as $city ) {
$city = trim(preg_replace('/\)/', '', $city)); // Remove trailing ')' and trim leading and trailing spaces
$a[2] = $city;
fputcsv( $file_with_fl, $a );
}
}
}
Checking for failure of fopen() and fputcsv() left as an exercise for the reader.
You can use file_put_contents(file, string, FILE_APPEND) to add a line to the end of a file.
The rest is just processing the Calgary (Forest Lawn / Dover / Erin Woods) part of your string.
$string = 'CA,T2B,Calgary (Forest Lawn / Dover / Erin Woods),Alberta,AB,Calgary,,,,51.0209,-113.981,6';
//test if string needs processing
//if not, write straight to new file
if(strpos($string,'/') === false){
file_put_contents("fileWithoutFL.txt" , $string , FILE_APPEND);
}
//process
else{
//get all the parts split by comma
//$parts[2] is the one you need processing
$parts = explode(',',$string);
//clean up $part[2], replacing ( , ) with *
//then split on the *
$com=explode('*',str_replace(['(','/',')'],'*',$parts[2]));
//loop $com, creating new arrays by replacing $part[2] in the original array
foreach($com as $val){
if($val == '')continue;
//replace $part[2] cleaning up spaces
$parts[2] = trim($val);
//make a new line
$write = implode(',',$parts);
//write to the new file
file_put_contents("fileWithoutFL.txt" , $write , FILE_APPEND);
}
}
Now you can read every line of the original file and output to the new file. (Tip: use SplFileObject)
$file = new SplFileObject("fileWithFL.txt");
while (!$file->eof()) {
$string = $file->fgets();
// ... process here with previous code
}
$file = null;
Not the best answer but its works
$line = file_get_contents("test.txt");
$body = "";
if(false !== strpos($line,"/")) {
$split = preg_split("/[()]+/", $line,-1, PREG_SPLIT_NO_EMPTY);
$contains = explode("/",$split[1]);
$last = explode(",",$split[0]);
$lastvalue = end($last);
$search = array_search($lastvalue,$last);
unset($last[$search]);
$merge = implode(", ", $last);
$body .= $merge . $split[2] . " ";
foreach($contains as $contain) {
$body .= $split[0] . "," . $contain . $split[2] . " ";
}
if(file_put_contents("fileWithFL.txt",$body) !== false) {
echo $body;
} else {
echo "failed";
}
} else {
if(file_put_contents("fileWithoutFL.txt",$line) !== false) {
echo $line;
} else {
echo "failed";
}
}
Output :
CA, T2B,Alberta,AB,Calgary,,,,51.0209,-113.981,6 CA,T2B,Calgary ,Forest Lawn ,Alberta,AB,Calgary,,,,51.0209,-113.981,6 CA,T2B,Calgary , Dover ,Alberta,AB,Calgary,,,,51.0209,-113.981,6 CA,T2B,Calgary , Erin Woods,Alberta,AB,Calgary,,,,51.0209,-113.981,6

How to read a file and sum the number of that file in php

Let's say you have a file with the following structure: txt format
"id,name,value
1,Dan,150
2,Peter,300
3,Mark,400
4,Victor,600"
This function I used to read the file :
function readAFile()
{
$userfileInfo = fopen("peopleInformation.txt", "r") or die("Unable to open the file.");
//echo fread($userfileInfo, filesize("peopleInformation.txt"));
$theData = fread($userfileInfo, filesize("peopleInformation.txt"));
echo $theData;
fclose($userfileInfo);
}
Output:
"id,name,value 1,Dan,150 2,Peter,300 3,Mark,400 4,Victor,600"
How i will seperate 150, 300, 400, 600 and sum them in php.
It's a csv file, you can explode each line with , and sum the last item except the first header line.
$lines = file($file_path);
$lines = array_map(function($v){return explode(",",$v);},array_slice($lines,1));
echo array_sum(array_column($lines,2)) . PHP_EOL;
Try to use preg_match_all and RegEx
function readAFile()
{
$userfileInfo = fopen("peopleInformation.txt", "r") or die("Unable to open the file.");
//echo fread($userfileInfo, filesize("peopleInformation.txt"));
$theData = fread($userfileInfo, filesize("peopleInformation.txt"));
echo $theData;
preg_match_all('/\d+,.+,(\d+)/', $theData, $output);
$sum = 0;
foreach($output[1] as $value){
$sum = $sum + (int) $value;
};
//echo "Sum :".$sum;
fclose($userfileInfo);
}
You can use fgets function to read it line by it. Then you can easily use explode function to change the line into array. The last index in the array is your desired value.
something like below:
$theData = fopen("peopleInformation.txt", "rw");
fgets($theData); //skip the header.
$sum = 0;
while (! feof ($my_file))
{
$line = fgets($theData);
$array_val = explode($line);
$sum += (int)end($array_val);
}

php data from text file to multidimensional array doesnt work but no console errors

I've written some code to read in data from a text file.
The data looks like this:
11:12:12:test titel 1
12:13:13:test titel 2
13:14:14:test titel 3
the following code reads the date, splits it one string for each line, those go in one array. This works perfectly.
After this, it should devide each line again in string that go in an array, and all these arrays go into one multidimensional array.
This last part doesnt work...
I think it's strange that instead of errors, of half the page, it shows just an empty page...
also, I've tried putting some of the code in comment, and so I've narrowed it down a bit. I give you guys the commented code, but all the comments should go away, and it should work like that!
thanks!
<?php
$filename = "data.txt";
$fp = fopen($filename, "r");
$content = fread($fp, filesize($filename));
$lines = explode("\n", $content);
$parts = null;
fclose($fp);
print_r($lines);
echo sizeof($lines);
for ($i=0; $i < sizeof($lines)-1 ; $i++) { //the minus 1 corrects the empty line automatically added when saving the data.txt file
//$tempParts[] = explode(":", $lines[i]);
//array_push($parts, $tempParts);
}
//echo "<br/>"
echo "all parts: "
//for ($row=0; $row < sizeof($lines)-1; $row++) {
// for ($col=0; $col < sizeof($parts[$row]); $col++) {
//echo $parts[$row][$col];
// }
//}
?>
I think preg_split will do what you want.
$filename = "data.txt";
$fp = fopen($filename, "r");
$content = fread($fp, filesize($filename));
//$content = "11:12:12:test titel 1
12:13:13:test titel 2
13:14:14:test titel 3";
$arr = preg_split("/(:|\n)/" ,$content);
var_dump($arr);
See here: http://www.phpliveregex.com/p/hNH
Click on preg_split on the right side of the screen to make it work
Maybe this works better for you?
preg_match_all("/(\d+):(\d+):(\d+):(.*)/", $content, $arr);
Click preg_match_all:
http://www.phpliveregex.com/p/hNW
I'm not sure to understand exactly what you want but you can try this :
if (!$fp = fopen("data.txt","r")) {
die("fail to open");
}else {
$all = array();
$row = 1;
while(!feof($fp)) { // foreach line
$ligne = fgets($fp,255); // get line content
$cols = explode(':', $line); // gets cols
$all[$row++] = $cols; // put cols on current row
}
var_dump($all); // dump all data stored by row
fclose($fp);
}

Read file and store into a variable

<?php
$userName = array();
$tutorial = array();
$myFile = "students.txt";
$fh = fopen($myFile,'r');
while( !feof($myFile) ){
$userName[] = array(fgets($fh));//Save first line content
$tutorial[] = array(fgets($fh));//Save second line content
}
fclose($myFile);
echo "$userName";
echo "$tutorial";
?>
and my students.txt content
dasdsa
A
asdasd
D
How to read that and store into different array and print them out
your code should work as expected. I assume you're bit confused with echo "$userName"; output as it displays Array word. try var_dump($userName) instead
Do exactly as you've done, but change
$userName[] = array(fgets($fh));//Save first line content
$tutorial[] = array(fgets($fh));//Save second line content
to
$userName[] = fgets($fh);//Save first line content
$tutorial[] = fgets($fh);//Save second line content
(no need to keep the subitems in their own seperate array)
and print them out by either using print_r, or iterate through them:
for ($i = 0; $i < count($userName); $i++) {
echo $userName[$i] . " - " . $tutorial[$i];
}
$text = file_get_contents('students.txt');
$text = explode("\n",$text);
$output = array();
foreach($text as $line)
{
$output[] = $line;
}
Use function file() in PHP
file — Reads entire file into an array
$array_lines = file('students.txt');
$count = count($array_lines);
$first_arr = array();
$sec_arr = array();
foreach ($array_lines as $i => $line){
if($i%2) $first_arr[] = $line;
else $sec_arr[] = $line;
}
print_r($first_arr);
print_r($sec_arr);
With file() function every line is read as element in array. You can check it with:
print_r($first_arr);

In PHP how to sort a file in reverse?

i have a text (text.txt) file like this:
shir
beer
geer
deer
i have also a php page with that source:
<?php
foreach (glob("*.txt") as $filename) {
$file = $filename;
$contents = file($file);
$reverse = array_reverse($file, true);
$string = implode("<br>" , $contents);
echo $string;
echo "<br></br>";
}
?>
I want that in the php page it will show:
deer
geer
beer
shir
from the end of the file to the beginning.
thank you
Looks like you are reversing the file name and not the contents.
Do
$reverse = array_reverse($content); // you can drop 2nd arg.
$string = implode("<br>" , $reverse);
in place of
$reverse = array_reverse($file, true);
$string = implode("<br>" , $contents);
Also you can remove the temp variables from you script and do:
foreach (glob("*.txt") as $filename) {
echo implode("<br>" , array_reverse(file($filename))) . "<br></br>";
}
<?php
foreach (glob("*.txt") as $filename) {
$file = $filename;
$contents = file($file);
$reverse = array_reverse($contents, true);
$string = implode("<br>" , $reverse);
echo $string;
echo "<br></br>";
}
?>
Your result was a $contents, without reverse.

Categories