including leading whitespaces when using fgets in php - php

I am using PHP to read a simple text file with the fgets() command:
$file = fopen("filename.txt", "r") or exit('oops');
$data = "";
while(!feof($file)) {
$data .= fgets($file) . '<br>';
}
fclose($file);
The text file has leading white spaces before the first character of each line. The fgets() is not grabbing the white spaces. Any idea why? I made sure not to use trim() on the variable. I tried this, but the leading white spaces still don't appear:
$data = str_replace(" ", " ", $data);
Not sure where to go from here.
Thanks in advance,
Doug
UPDATE:
The text appears correctly if I dump it into a textarea but not if I ECHO it to the webpage.

Function fgets() grabs the whitespaces. I don't know what you are exactly doing with the $data variable, but if you simply display it on a HTML page then you won't see whitespaces. It's because HTML strips all whitespaces. Try this code to read and show your file content:
$file = fopen('file.txt', 'r') or exit('error');
$data = '';
while(!feof($file))
{
$data .= '<pre>' . fgets($file) . '</pre><br>';
}
fclose($file);
echo $data;
The PRE tag allows you to display $data without parsing it.

Try it with:
$data = preg_replace('/\s+/', ' ', $data);
fgets should not trim whitespaces.

Try to read the file using file_get_contents it is successfully reading the whitespace in the begining of the file.
$data = file_get_contents("xyz.txt");
$data = str_replace(" ","~",$data);
echo $data;
Hope this helps

I currently have the same requirement and experienced that some characters are written as a tab character.
What i did was:
$tabChar = ' ';
$regularChar = ' '
$file = fopen('/file.txt');
while($line = fgets($file)) {
$l = str_replace("\t", $tabChar, $line);
$l = str_replace(" ", $regularChar, $line);
// ...
// replacing can be done till it matches your needs
$lines .= $l; // maybe append <br /> if neccessary
}
$result = '<pre'> . $lines . '</pre>';
This one worked for me, maybe it helps you too :-).

Related

Can't get whitespace added to string in PHP

I"m trying to make a web form that outputs to flat text file line by line what the input to the web form is. Several of the fields are not required but the output file must input blank spaces in for whatever is not filled out. Here is what I'm trying:
$output = $_SESSION["emp_id"];
if(!empty($_POST['trans_date'])) {
$output .= $_POST["trans_date"];
}else{
$output = str_pad($output, 6);
}
if(!empty($_POST['chart'])) {
$output .= $_POST["chart"];
}else{
$output = str_pad($output, 6);
}
write_line($output);
function write_line($line){
$file = 'coh.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new line to the file
$current .= $line . PHP_EOL;
// Write the contents back to the file
file_put_contents($file, $current);
}
However, when I check my output the spaces don't show up. Any ideas on what's going on with this? Thanks in advance!
str_pad is padding with spaces, not adding spaces. You're padding an existing value with spaces so that it is 6 characters long, not adding 6 whitespaces to the value. So if $_SESSION["emp_id"] is 6 characters long or more, nothing will be added.
str_pad() won't add that number of spaces, but rather makes the string that length by adding the appropriate number of spaces. Try str_repeat():
$output = $_SESSION["emp_id"];
if(!empty($_POST['trans_date'])) {
$output .= $_POST["trans_date"];
}else{
$output = $output . str_repeat(' ', 6);
}
if(!empty($_POST['chart'])) {
$output .= $_POST["chart"];
}else{
$output = $output . str_repeat(' ', 6);
}
write_line($output);
function write_line($line) {
$file = 'coh.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new line to the file
$current .= $line . PHP_EOL;
// Write the contents back to the file
file_put_contents($file, $current);
}
Cheers!

Php write strange character on txt file

I to everyone, when i execute thi code for write on a file:
$fileTXT = 'prodotti.txt';
$newfileTXT = 'prodotti_2'.date("d-m-Y_h_m_s").'.txt';
if (!copy($fileTXT, $newfileTXT)) {
echo "Impossibile continuare, impossibile creare file TXT.";
exit;
}
$towriteinfile = "";
$fp = fopen($path . $filename, "r") or die("Couldn't open $filename");
$fpTXT = fopen($newfileTXT, 'w') or die("Couldn't open $newfileTXT");
while (!feof($fp)) {
$line = fgets($fp, 1024);
$arr = explode("\t", $line);
$arr[7] = '<img src="http://link/imgHigh/' . $arr[7] . '.jpg" />;';
echo "Prodotto: ".$arr[4]."<br>";
foreach ($arr as $fields) {
fwrite($fpTXT, $fields.";");
}
fwrite($fpTXT, "\n");
}
fclose($fpTXT);
fclose($fp);
I have thi result on txt file:
175;13563;desc;01;category;..............c etc etc.....
mercato.㰻浩⁧牳㵣栢瑴㩰⼯睷⹷獯畣慬楴挮浯椯⽴慣⽴浩䡧杩⽨ ㄀⸀㄀  ⸀砀砀 漀欀ഀ਀樮杰•㸯㬻
the html code for image is written as chinese caharcter, why?
Do you want to add content to the end of $newFileTXT from $filename ?
IF so, you should change:
$fpTXT = fopen($newfileTXT, 'w') or die("Couldn't open $newfileTXT");
to
$fpTXT = fopen($newfileTXT, 'a') or die("Couldn't open $newfileTXT");
The file is probably interpreted as unicode (probably UTF-8). In unicode, characters can consist of multiple bytes. When you read the file, you just read 1024 bytes, which can result in half a unicode character at the end of the part that you read, and the other half at the start of the next part. When you start adding new characters inbetween, you get other unicode sequences instead, causing the text to be a complete mess.
I have resolved the problem, i have passed any line to this function:
function cleanString($string){
$string = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $string);
return $string;
}
My old string contained binary chars, i have cleaned the string and now all is ok

changing new line to <br> in text area

My problem is pretty simple. I want to change new lines in text area to <br> tags BUT I need the final string to be one-line text. I tried using nl2br function but as a result I get string with <br> tags and new lines. I also tried to simply replace &#013 or &#010 symbols with <br> using str_replace but it doesn't work.
Here is sample of my latest code:
Godziny otwarcia: <textarea name="open" rows="3" cols="20">'."$openh".'</textarea>
<input type="submit" name="openb" value="Zmień"/><br>
if($_POST['openb']) {
$open = $_POST['open'];
str_replace('&#010', '<br>', $open);
change_data(21, $open);
}
The $openh is result of this:
$tab = explode('<br>', $openh);
$openh = null;
for($i=0;$i<count($tab);$i++)
$openh = $openh . $tab[$i] . '&#013';
(yes, I know i could use str_replace, don't ask why I did it this way)
and the original $openh is $openh = 'Pon-pt 9:00-17:00<br>Środa 12:00-17:00'
Also you may want to see my change_data function as it is connected to why i need the string to be in one line, so here it is:
function change_data($des_line, $data) {
$file = 'config.php';
$lines = file($file);
$i=1;
foreach($lines as $line_num => $line) {
$wiersz[$i] = $line;
$i++;
}
$change = explode("'", $wiersz[$des_line]);
$wiersz[$des_line] = $change[0] . "'" . $data . "'" . $change[2];
$i = 1;
$f = fopen($file, w);
while($i <= count($wiersz)) {
fwrite($f, $wiersz[$i]);
$i++;
}
fclose($f);
header('location: index.php?p=admin');
}
I'm not PHP specialist so sometimes I do things little "hard" way.. I had huge problems with reading file config.php line by line and these are results of my few-hours effort :(
have you tried the php constant PHP_EOL? in you str_replace code?
$open=str_replace(PHP_EOL,"<br>",$_POST["open"]);
There is a ready made PHP function for that named nl2br
Source: https://stackoverflow.com/a/16376133/469161

php remove a line after specific words with str_replace

there is text in file as example:
<div class="from">jack</span></div>
hey u
<div class="from">ron</span></div>
bye
i am trying to delete the new line tag after "" and replace "|"
the result i need is:
<div class="from">jack</span></div>|hey u
<div class="from">ron</span></div>|bye
i tried this but think i got it wrong because it do the job.
$string = file_get_contents($filename);
$string = str_replace('/(<\/span><\/div>\r\n)', '|', $string);
file_put_contents($filename, $string);
what is the correct way?
thanks
<?php
$string = '<div class="from"><span>jack</span></div>
hey u';
echo preg_replace('/\r\n/', '|', $string);
$file_handle = fopen($filename, "r");
$text = "";
while (!feof($file_handle)) {
$line = fgets($file_handle);
if (strpos($line,'<div>') !== false) {
$line = preg_replace('/\r\n/', '|', $line)
}
$text .= $line;
}
file_put_contents($filename, $text);
fclose($file_handle);
Hows that for reading the file line by line, if the line has a tag, it replaces \n\r, and then at the end writes all of the lines back into the file.
It depends on what line ending is used, there's three possible ones, \n, \r\n, and \r.
Try this:
$string = str_replace('/(<\/span><\/div>\n)', '|', $string);
Also the first slash in that string is suspect, so try this:
$string = str_replace('(<\/span><\/div>\r\n)', '(<\/span><\/div>|', $string);

Parsing file in PHP; how to detect newlines?

I've got a problem where I'm trying to read a text file like this:
Joe
Johnson
Linus
Tourvalds
and while parsing it in php, I need to be able to detect the newlines. I'm trying to correctly define $newline. I'm looping through the array of lines in the $file variable.
while($line = next($file))
if($line = $newline)
echo "new line";
The problem is that I can't seem to match the newline character. I know that it is actually showing up in the $file array, because this:
while($line = next($file))
echo $line;
outputs the file verbatim, with newlines and all. I've already tried "\n", " ", and I'm not sure what to try next. A little help?
$file = file("path/to/file.txt");
// Incase you need to call it multiple times ...
function isNewLine($line) {
return !strlen(trim($line));
}
foreach ($file as $line) {
if (isNewLine($line)) {
echo "new line<br/>";
}
}
Maybe something like this would work for you?
while($line = next($file)) {
if(in_array($line, array("\r", "\n", "\r\n"))) {
echo "new line";
}
}
I think this solution may help you guys. This works if you are parsing csv that is generated from Mac or windows. Reading csv with multilines created in Mac, gives problem i.e. you cannot read each line in a loop but all csv data is read as single line.
This problem is solved by following solution:
//My CSV contains only one column
$fileHandle = fopen("test.csv",'r');
$codesArray = array();
count = 0;
while (!feof($fileHandle) ) {
$line = fgetcsv($fileHandle);
if($line[0]!="") {
$data = str_replace("'", "", (nl2br ($line[0])));
$dataArray = explode('<br />' ,$data );
foreach($dataArray as $data) {
$codesArray[] = trim($data);
}
}
}
echo "<pre>";
print_r($codesArray);

Categories