Using PHP to Seperate Results of a txt file - php

I am trying to display the last 10 lines of a File and from there take those results and break them down to 10 individual lines..
Currently the code I have found from examples is:
$filearray = file("test.txt");
$lastfifteenlines = array_slice($filearray,-10);
echo implode($lastfifteenlines, "\n")
It display's the 10 items I need however it does not break them down onto individual lines the current results are:
1.0.0.11 1.0.0.12 1.0.0.13 1.0.0.14 1.0.0.15
I need that to instead display as:
1.0.0.11
1.0.0.12
1.0.0.13
1.0.0.14
1.0.0.15
Thanks in Advance for the Asistance!

\n is plain whitespace in html.
use echo implode("<br>", $lastfifteenlines) or put them in to separate divs, use a list (ul+li), etc..

use the explode function, like this
$filearray = file("test.txt");
$lastfifteenlines = array_slice($filearray,-10);
$impfile = implode($lastfifteenlines, '\n');
$lines = explode('\n', $impfile);
foreach ($lines as $line){
echo $line."<br>";
}
outpu will be
1.0.0.11
1.0.0.12
1.0.0.13
1.0.0.14
1.0.0.15
i hope that's what you want :)

Your code works fine. You just can't see the line breaks because HTML doesn't treat them as line breaks.
See the HTML source code in your browser to see the line breaks.
Possible solution
echo <pre> and </pre> tags before and after the implode.
Add header("Content-Type: text/plain"); before any output. It will cause the browser to parse the document as a text file and not HTML (note that no HTML tags will be parsed by the browser)
implode the array with a different string, <br>, which will cause a line break in HTML.
Also, your syntax is wrong, it's
implode($glue, $pieces);
And not
implode($pieces, $glue);

Related

PHP & HTML <a href> leaving extra space?

I have the following PHP code
$links = fopen("./links/links.txt", "r");
if ($links) {
while (($line = fgets($links)) !== false) {
$linkData = explode(" ", $line);
/// The line below is the problematic one
echo "<a href='".$linkData[0]."' class='links-item'>".$linkData[1]."</a><br>";
}
fclose($links);
} else {
die('Error opening file, try refreshing.');
}
You can see I've seperated the line I'm having issues with. I have the following file links.txt
http://example.com Example
http://example2.com Example2
Basically this will add the URL in the text file to an anchor tag, and it'll add the text next to it, as the anchor display text. It works, but for some reason, every anchor tag ends with a space, except the last one. Anyone know why this is and how I can fix it?
The string that fgets() returns includes the newline that separates the lines. This will be at the end of $linkData[1], so you're writing
<a href='http://example.com' class='links-item'>Example
</a><br>
to the output.
You could instead use fgetcsv(), specifying space as the field delimiter. This will explode the line for you and automatically ignores the newlines.
while (($linkData = fgetcsv($links, 0, " ")) !== false) {
echo "<a href='".$linkData[0]."' class='links-item'>".$linkData[1]."</a><br>";
}
fgets() captures newlines as well as word characters into the string. Use the trim function to remove unwanted whitespace:
echo "<a href='".trim($linkData[0])."' class='links-item'>".trim($linkData[1])."</a><br>";
Alternatively, as #Barmar noted, you could use fgetcsv function
use
var_dump($linkData);
To see what does fgets() returns. Maybe there are unexpected characters.
Consider to use more advanced file formatting, for example you can use csv format and use http://php.net/manual/en/function.fgetcsv.php to retrieve results from file.

Why does it add the text at the beginning of next line, and not the end of the right one?

Needed solution:
I am working with a simple PHP script that should:
Add "value4:::" at the end of the first line in a file
Add ":::" at the end of all the next lines
I am novise in programming, and have sit here for two days trying to figure this out. Might be a little detail, or it might be totally wrong way of doing this task.
It might be wrong way to do this, or may be a regex problem? I really don't know.
I kindly ask you to help me with the solution.
Information:
The file newstest.db looks like this:
ID:::value1:::value2:::value3:::
1:::My:::first:::line:::
2:::My:::second:::line:::
3:::Your:::third:::line:::
And using this php script I'd like to make it look like this:
ID:::value1:::value2:::value3:::value4:::
1:::My:::first:::line::::::
2:::My:::second:::line::::::
3:::Your:::third:::line::::::
Problem:
So far I have almost got it, but I am confused to why it adds the "value4:::" to the beginning of the second line, and then add ":::" at the beginning (not end) of all of the rest of the lines.
So I get a file that looks like this:
ID:::value1:::value2:::value3:::
value4:::1:::My:::first:::line:::
:::2:::My:::second:::line:::
:::3:::Your:::third:::line:::
I thought that:
$lineshere = 'Some text here:::';
$lines1 = $linehere.'value4:::';
would output "Some text here:::value4:::"
May be the problem is due to this way of adding line after line?
$lines = '';
$lines.= 'My test';
$lines.= ' is here';
echo $lines;
I am a novise in programming, so I might have used totally wrong functions tec to make this work.
But in this case it seams to add a space or line break/ line end in the wrong place.
My try on this solution:
<?php
// specify the file
$file_source="newstest.db";
// get the content of the file
$newscontent = file($file_source, true);
//set a start value (clear memory)
$lines ='';
// get each line and treat it line by line.
foreach ($newscontent as $line_num => $linehere) {
// add "value4:::" at the end of FIRST line only, and put it in memory $lines
if($line_num==0) {
$lines.= $linehere.'value4:::';
// Just to see what the line looks like
//echo 'First line: '.$lines.'<br /><br />';
}
// then add ":::" to the other lines and add them to memory $lines
if($line_num>0) {
$lines1 = $linehere.':::';
$lines.= $lines1;
//just look at the line
//echo 'Line #'.$line_num.': '.$lines1.'<br /><br />';
}
}
//Write new content to $file_source
$f = fopen($file_source, 'w');
fwrite($f,$lines);
fclose($f);
echo "// to show the results ar array<br /><br />";
$newscontentlook = file($file_source, true);
print_r(array_values($newscontentlook));
?>
This is actually very easy to achieve with file_get_contents and preg_replace, i.e:
$content = file_get_contents("newstest.db");
$content = preg_replace('/(^ID:.*\S)/im', '$1value4:::', $content);
$content = preg_replace('/(^\d+.*\S)/im', '$1:::', $content);
file_put_contents("newstest.db", $content);
Output:
ID:::value1:::value2:::value3:::value4:::
1:::My:::first:::line::::::
2:::My:::second:::line::::::
3:::Your:::third:::line::::::
Ideone Demo
the function file() gives you the file in an array with each line being an element of the array. Each ending of the line (EOL) is included in the elements. So appending text to that line will be after the EOL, and thus effectively on the beginning of the next line.
You can either choose to not use file() and explode the text yourself on the EOL, so the EOL is no longer part of the array element. Then edit the elements, and implode the array again.
Or fopen() the file, and fread() through it yourself. The latter option is preferred, as it won't load the entire file into memory at once.
I think the problem is in your loop through the lines read by file() function:
foreach ($newscontent as $line_num => $linehere) {
...
$linehere contains a newline at the end, so you should simply chop it before using it:
foreach ($newscontent as $line_num => $linehere) {
$linehere = chop($linehere);
...
If you don't chop the line contents, when you concatenate a string to it, you'll get:
LINE_CONTENTS\nSTRING_ADDED
which, when printed, will be:
LINE_CONTENTS
STRING_ADDED
Hope this helps...

file_get_contents() skipping text between <> tag

I am trying to read a .tsv file using PHP. I am using the simplest method of file_get_contents() but it is skipping any text between <> tags.
Following is the format of my .tsv file
<id_svyx35_88c_avbfa5> <Kuldeep_Raval> rdf:type <wikicat_Delhi_Daredevils_cricketers>
Following is the code I am using
$filename = "access_s.tsv";
$content = file_get_contents($filename);
//Split file into lines
$lines = explode("\n", $content);
echo $content;
On reading it, the output is just
rdf:type
Please help in what can be the solution to read the line as it is?
Try to apply htmlspecialchars() to $content:
$filename = "access_s.tsv";
$content = htmlspecialchars(file_get_contents($filename));
//Split file into lines
$lines = explode("\n", $content);
echo $content;
Reference on php.net
The tags have always been there, the browser just does not show them. Just like with any valid HTML tag, you can see them when viewing the source code of the website.

Reading from a .txt file - concatenate - echoing content puts a space in automatically?

I'm reading content from a text file which I'm showing on a page later, this is my code:
$lines = file("content.txt");
$i=1;
foreach($lines as $line ){
$var["line" . $i] = $line;
$i++;
}
extract($var);
The text file includes content in this format:
bla1
bla2
and so on, there's no space behind the domains just a linebreak, now I want to concatenate the content and show it, so I do this:
$as1 = $line1.$line2;
echo $as1;
But instead of the expected result
Bla1Bla2
I get
Bla1 Bla2
What am I doing wrong ? I can assure that there's no space in the text file not behind nor infront of the content.
There's no space; but unless you tell the file() function otherwise, there is a line feed at the end of each line
$lines = file("content.txt", FILE_IGNORE_NEW_LINES);
A browser will render a line feed as a space, unless inside a or block
use trim for this situation
$as1 = trim($line1).trim($line2);
echo $as1;
You could try trimming your input...
$lines = file("content.txt");
$i=1;
foreach($lines as $line ){
$var["line" . $i] = trim($line);
$i++;
}
extract($var);

I am using fgets() to read in a line in PHP. But i am getting a wierd result?

$size = intval(trim(fgets($fp,4)));
$triangle = range(1,$size);
for($j=0;$j<$size;$j=$j+1)
$triangle[$j] = split(" ",trim(fgets($fp,400)));
This code reads in the number of lines to read, then reads them one by one. Issue is, when first input line ends in space, it reads that space as a new line.
you can read full file content by file_get_contents.
<?php
$content= file_get_contents('myfile.txt');
echo $content;
?>

Categories