Echo of array doesn't do paragraphs on the right places - php

I know this isn’t a very useful question for most people but I have dedicated a lot of time to solve a small problem and I didn’t get the results that I wanted, so I need your help:
<?php
$lines = file('temphum.txt');
$result = array_reverse($lines);
for($i=0; $i<count($result);$i=$i+4){
$cenas= $result[$i]."ºC";
$contentsite= nl2br($cenas);
echo $contentsite ;
}
?>
This code prints this:
25ºC24
ºC23
ºC22
ºC21
ºC
Instead of this:
25ºC
24ºC
23ºC
22ºC
21ºC
What is the problem?

You append the °C sign after the newline at the end of the string.
<?php
$lines = file('temphum.txt', FILE_IGNORE_NEW_LINES);
$result = array_reverse($lines);
for($i=0; $i<count($result);$i=$i+4){
echo $result[$i]."ºC"."<br>";
}

Related

PHP - How can I make calculations with numbers I get from a text file?

So I have a task where I should read a text file in php, containing students IDs and their grades, separated by vertical lines. It looks something like that:
12345|4|2|1|0|4
45678|1|2|3|4|4
78901|5|5|5|5|4
The program should print the amount of students there are on the file, which I managed to do by simply echoing the amount of lines. However, I should also print the sum of the grades for each student, and I simply can't find a way to do it. Do I get the characters by order on the line or something similar? I've been struggling with this for a day now and I only got as far as this:
<?php
$file="exam.txt";
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
$line = fgets($handle);
$linecount++;
}
echo "total_students was $linecount:";
$homepage = file_get_contents('exam.txt');
echo $homepage;
?>
This code only prints the page and the amount of lines, nothing more.
So after I was guided in the right direction I managed to come up with a solution!
<?php
$file="exam.txt";
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
$line = fgets($handle);
$linecount++;
}
echo "total_students was $linecount:\n";
$lines = file('exam.txt');
$sum = 0 ;
foreach ($lines as $line){
$var = explode("|", $line);
$sum = $var[1]+$var[2]+$var[3]+$var[4]+$var[5];
$all += $sum;
echo "$var[0]: $sum points\n";
}
$average = $all / $linecount;
echo "The average score was $average points."
?>
I exploded each line as an array divided by the "|" symbol, then I printed the student ID from the [0] of the array, and summed the rest. After that I summed the sums and thus found the average.

Read from a text file and post the first 50 lines into another text file?

I have a text file and it is called 'Store.txt'.
I would like to know how I can read from this file and then grab the first 50 lines of numbers/text
and insert them into another text file.
I have little code because I'm not exactly sure how to go about it and I've been searching online but couldn't find much I believe an if statment is the answer?
Any way I have gave it ago but sadly it hasn't worked.
Here is how I got on-
<?php
$fileToOpen = fopen('Store.txt', 'r');
$return = '';
$count = 0;
$return. = $fileToOpen. "\n";
if ($count >= 50)
break;
}
file_put_contents($return, "Store2nd.txt");
fclose($fileToOpen);
?>
Thank you in advance for any help. (:
This will copy upto the first 50 lines without reading in the complete file:
<?php
$fileToOpen = fopen('Store.txt', 'r');
$outputFile = fopen('Store2nd.txt', 'w');
$count = 0;
while (!feof($fileToOpen)) { // We'll copy the whole file ...
if ($count++ >= 50) // ... or the first 50 lines, whichever is less
break;
$line = fgets($fileToOpen);
fwrite($outputFile, $line);
}
fclose($fileToOpen);
fclose($outputFile);
?>
Please give this a try:
<?php
$lines = file('Store.txt'); // make file content an array
$result = array_slice($lines,0,50); // take the first 50 lines
file_put_contents('Store2nd.txt', implode('', $result)); // output
?>
A better way would probably be to do a foreach loop for your text.
Then add $count++ in your loop so that the $count = 0; you've set up will increase.
Right now with your code, nothing is increasing, so $count never reaches 50.
Cheers.

PHP: Run through multiple URLs and display their content

Let's say we have an URL looking something like this.
http://domain.com/index.php?p=1&u=A1b2C3d4E5f6G7h8I9j
The number span after ?p= goes from 1 to 999 and the rest is unchanged.
Every URL contains one short line of text.
What would a script look like which can run through all 999 URLs and display their contents?
It would be easy. You can use the FOR LOOP.
<?php
for($i=1; $i < 1000; $i++) {
echo file_get_contents('http://domain.com/index.php?p=' . $i . '&u=A1b2C3d4E5f6G7h8I9j');
}
Documentations:
For Loop
file_get_contents() method
This is going to be resource intensive. But taking a shot in the dark, this should work:
<?php
$urlContent = array();
$urlStart = 'http://domain.com/index.php?p=';
$urlEnd = '&u=A1b2C3d4E5f6G7h8I9j';
$count = 1;
while($count <= 999){
$urlContent[$count] = file_get_contents($urlStart.$count.$urlEnd);
$count++;
}
foreach($urlContent as $content){
echo $content.'\n';
}
?>
This code is Untested

PHP Array Looping & Exploding

I'm not very experienced in using PHP, but I'm having a hard time thinking of a way to do this. I'm reading from a file and exploding on ":" as you can see here.
<?php
$datainfo = file('data.txt');
for($i = 0; $i < count($datainfo); $i++){
$expdata = explode(':', $datainfo[$i]);
}
?>
The issue is that I need to reference specific indexes of the resulted explosion like this.
<p> <?php echo $expdata[1] ?> </p>
I'm getting back an array of the last line inside the data.txt file. I know why It's happening, I just don't know how to get what I want here. (Sorry Very New). Data.txt contain the following.
name:Octopod Juice Stand
balance:20
price:0.5
customers:12
starting:2014-05-26
end: 2014-09-01
juice:15.25
fruit:10
Change your code to
<?php
$datainfo = file('data.txt');
$expdata = array();
for($i = 0; $i < count($datainfo); $i++){
$expdata[] = explode(':', $datainfo[$i]);
}
?>
And then to get the first label.
<p><?php echo $expdata[0][0]; ?></p>
Or the first value
<p><?php echo $expdata[0][1]; ?></p>

PHP Grab last 15 lines in txt file

Thank you for taking the time to read this and I will appreciate every single response no mater the quality of content. :)
Using PHP, I'm trying to get the last 15 lines of a text document (.txt) and store that data into a php variable. I understand that this is possible, however when I do get the last 15 lines, is it possible to retain the order? For example:
text document:
A
B
C
When I grab the text document from the last 15 characters, I don't want the echo to end up like:
C
B
A
All assistance is appreciated and I look forward to your replies; thank you. :) If I didn't explain anything clearly and/or you'd like me to explain in more detail, please reply. :)
Thank you.
Try using array_slice, which will return a part of an array. In this case you want it to return the last 15 lines of the array, so:
$filearray = file("filename");
$lastfifteenlines = array_slice($filearray,-15);
If you don't mind loading the entire file into memory:
$lines = array_slice(file('test.txt'), -15);
print_r($lines );
If the file is too large to fit into memory you can use a circular method:
// Read the last $num lines from stream $fp
function read_last_lines($fp, $num)
{
$idx = 0;
$lines = array();
while(($line = fgets($fp)))
{
$lines[$idx] = $line;
$idx = ($idx + 1) % $num;
}
$p1 = array_slice($lines, $idx);
$p2 = array_slice($lines, 0, $idx);
$ordered_lines = array_merge($p1, $p2);
return $ordered_lines;
}
// Open the file and read the last 15 lines
$fp = fopen('test.txt', 'r');
$lines = read_last_lines($fp, 15);
fclose($fp);
// Output array
print_r($lines);
This method will also work if the file has less than 15 lines- returning an array with however many lines are in the file.
You can use fseek with a negative position to seek backwards through the file, counting newlines as you go.
I'm too tired to write up copy/past-able code, but there are some examples in the comments to the manual page for fseek that are very close to what you want.
If the file isn't bigger than available memory you can do this:
$fArray = file("filename");
$len = sizeof($fArray);
for($i=$len -15;$i<$len ;$i++)
{
echo $fArray[$i];
}
If you have a file that is hundreds of megabytes :
$rc = fopen("file","r");
for ($i=0; $line = fgets($file) ;$i++)
{
if ($i%15 == 0)
{
$last15 = array();
}
$last15[] = $line;
}
echo join("\n",$last15);
the longer array solution:
array_slice(explode("\n",file_get_contents($file)),-15);
the shorter array solution:
array_slice(file($file),-15);
This code will open the file, show the total lines, show the header of file and show the last lines of file defined in $limit.
<?php
// open the file in read mode
$file = new SplFileObject('file.csv', 'r');
// get the total lines
$file->seek(PHP_INT_MAX);
$last_line = $file->key();
echo $last_line;
echo "<br>";
// Rewind to first line to get header
$file->rewind();
// Output first line if you need use the header to make something
echo $file->current();
echo "<br>";
// selecting the limit
$limit = 6;
// selecting the last lines using the $limit
$lines = new LimitIterator($file, $last_line - $limit, $last_line);
//print all the last 6 lines array
//print_r(iterator_to_array($lines));
//echo "<br>";
// Loop over whole file to use a single line
foreach ($lines as $line) {
print_r($line);
echo "<br>";
}

Categories