read row and columns of text file in php - php

I have a text file the contents of which are as follows:
120MB 130MB 140MB 140MB
10% 20% 30% 40%
I have a php code which reads the file and prints the column.
<?php
$lines = file('test_ssh.txt');
foreach ($lines as $line) {
$parts = explode(' ', $line);
echo $parts[2] ;
}
?>
by this code I can read columns from the first row as and when required(i.e, if I need to popultae 1st column from 1st row in html table, I can do so by $parts[0])
but I am not able to read second line column by column(i.e. if I just need to read 1st column from 2nd row), I am not able to do it, I just get blank value.
Do I need some 2-D array to read lines and column separately or there is another easier way ? Please help with your expertise.

Not sure why you would only want to print one item from the first line and all the occurances from the second. But if this was really what you were asking how to do here is one way.
<?php
$lines = file('test_ssh.txt');
foreach ($lines as $lineNo => $line) {
$parts = explode(' ', $line);
if ( $lineNo < 1 ) {
echo $parts[2] . PHP_EOL;
} else {
foreach( $parts as $col ) {
echo $col . ' ';
}
}
}
Result
140MB
10% 20% 30% 40%
After your comment below
Is this what you wanted
$lines = file('test_ssh.txt');
foreach ($lines as $line) {
if ( $line == PHP_EOL ) { continue; } // avoid blank lines causing issues
$columns = explode(' ', $line);
echo '<tr>' . PHP_EOL;
foreach( $columns as $col ) {
echo '<td>' . trim($col) . '</td>';
}
echo PHP_EOL . '</tr>' . PHP_EOL;
}
RESULT
<tr>
<td>120MB</td><td>130MB</td><td>140MB</td><td>140MB</td>
</tr>
<tr>
<td>10%</td><td>20%</td><td>30%</td><td>40%</td>
</tr>
<tr>
<td></td>
</tr>
ignore the PHP_EOL in the table output, they are there just to make the output look human readable.
Having reread the updated question, maybe this is what you want
function getColfromBothLines($col, $lines)
{
$lin1 = explode(' ', $lines[0]);
$lin2 = explode(' ', $lines[1]);
return $lin1[$col] . ' - ' . $lin2[$col];
}
$lines = file('test_ssh.txt');
echo getColfromBothLines(0, $lines).PHP_EOL;
echo getColfromBothLines(1, $lines).PHP_EOL;
echo getColfromBothLines(2, $lines).PHP_EOL;
RESULT
120MB - 10%
130MB - 20%
140MB - 30%

Try this! First foreach for lines and second for explodes.
<?php
$lines = file('test_ssh.txt');
foreach ($lines as $line) {
$parts = explode(' ', $line);
foreach ($parts as $part) {
echo $part;
}
}
Do not close php tag :)

Try this.
$array = explode("\n", file_get_contents('file.txt'));

Related

Split a string 2 times and put it in a table

Ok i have a string which needs to be splitted 2 times.
First time by whitespaces and second time by commas. So i can put it in a table.
I managed to split the string by whitespaces and put it in the first column of the table but i struggle to split it for the second time and put the values in the right column.
Here the snippets of what i already got:
<?php for ($i = 0; $i < sizeof($volumes); $i++) {
echo "<tr><td>" . $volumes[$i] . "</td></tr>";
} ?>
When you render the table rows you should split each volume by comma. I don't understand exactly all the retrieved rows or what is the logic behind your code but this bunch of code should do what you need:
<?php
for ($i = 0; $i < sizeof($volumes); $i++) {
echo '<tr>';
$volumeData = explode(',', $volumes[$i]);
foreach ($volumeData as $volume) {
echo '<td>' . $volume . '</td>';
}
echo '</tr>';
}
?>
Are you sure the string you provided is accurate? I think there's a coma missing between the size of SystemReserved and the label of the next drive. If that's the case - the code should be something like this:
First we 'explode' the string to create an array, then use array chunk to split it into arrays with seven entries each. And then render it:
$string = 'L,Logs,NTFS,Healthy,OK,9.73,9.77 ,SystemReserved,NTFS,Healthy,OK,0.16,0.49 ,C,LocalDisk,NTFS,Healthy,OK,18.19,29.74';
$array = explode(',', $string);
$results = array_chunk($array, 7, true);
?>
<table id="tbl_basic_volumes">
<tr>
<th>Buchstabe:</th>
<th>Name:</th>
<th>Filesystem:</th>
<th>Health Status:</th>
<th>Operational Status:</th>
<th>Freier Speicherplatz:</th>
<th>Gesamter Speicherplatz:</th>
</tr>
<?php
foreach ($results as $result) {
echo '<tr>';
foreach ($result as $entry) {
echo '<td>'.$entry.'</td>';
}
echo '</tr>';
}
?>
</table>
You can escape the inner foreach loop using implode.
$str = "L,Logs,NTFS,Healthy,OK,9.73,9.77 ,SystemReserved,NTFS,Healthy,OK,0.16,0.49 C,LocalDisk,NTFS,Healthy,OK,18.19,29.74";
$rows = explode(' ', $str);
foreach ($rows as $row) {
echo '<tr><td>' . implode('</td><td>', explode(',', $row)) . '</td></tr>';
}
Or even replacing commas with </td><td> will also work:
$str = "L,Logs,NTFS,Healthy,OK,9.73,9.77 ,SystemReserved,NTFS,Healthy,OK,0.16,0.49 C,LocalDisk,NTFS,Healthy,OK,18.19,29.74";
$rows = explode(' ', $str);
foreach ($rows as $row) {
echo '<tr><td>' . str_replace(',', '</td><td>', $row) . '</td></tr>';
}

PHP Read Text File With Column Separated

I have a text file generated from our banking software which looks like this:
This is my code to print the text file contents line by line:
<?php
$myFile = "20151231.txt";
$lines = file($myFile);
foreach ($lines as $line_num) {
echo htmlspecialchars($line_num)."<br>";
}
It prints like this:
I just want each line that starts with:
====>
I want everything else deleted.
I tried a lot but failed to print lines with the columns separated as it looks in the text file image.
This is how I want each line to print:
====>0518 Intt on Consumer Loan 401010707 108,149.00
Your assistance regarding this will be highly appreciated.
You can print it as a table:
<?php
$myFile = "20151231.txt";
$lines = file($myFile);
echo '<table>';
foreach ($lines as $line_num) {
if (strpos($line_num, '====>') !== false) {
$str = trim(htmlspecialchars($line_num));
echo '<tr>';
echo '<td>' . getColumnText("/====>\d+/", $str) .'</td>';
echo '<td>' . getColumnText("/\s([a-zA-Z\s]+)/", $str) .'</td>';
$secondCol = getColumnText("/\s([0-9]+)/", $str);
echo '<td>' . $secondCol .'</td>';
$thirdCol = end(explode(" ", $str));
if (trim($secondCol) === $thirdCol) {
echo '<td style="text-align:right">' . str_repeat(" ", 10) .'</td>';
} else {
echo '<td style="text-align:right">' . str_repeat(" ", 10) . $thirdCol .'</td>';
}
echo '</tr>';
}
}
echo '</table>';
function getColumnText($pattern, $str) {
preg_match($pattern, $str, $matches);
return trim(current($matches));
}
yes you can do that with strpos or regularexpression and i am just writing code using strpos
<?php $myFile = "text.txt";
$lines = file($myFile);
echo '<table cellspacing="20">';
$linenum = 1;
foreach ($lines as $line_num) {
echo '<tr>';
// check whether line conatain ====>, if you want to check starting of line then just put 0 instead of false in following condition
if(strpos($line_num,'====>')!==false)
{
$texts= substr($line_num, strpos($line_num,'====>')+5);
$textarr = explode(" ", $texts);
echo '<td>'.$linenum.'</td>';
foreach($textarr as $arr)
{
echo '<td>'.$arr.'</td>';
}
$linenum++;
//print_r($textarr);
//echo htmlspecialchars($line_num)."<br>";
}
}
echo '<table>';

How to aggregate (sum) rows in a CSV file and print as a table using PHP

I am trying to use PHP to interpret a simple CSV log file and print it out as a table.
The file has three columns - a name, followed by two columns with a 1 or a 0 in either.
E.g.
Test,1,0
Test,0,1
Test2,1,0
Test3,1,0
Test3,0,1
Test3,1,0
Test3,0,1
The goal is to sum all identical rows together to give this:
Test,1,1
Test2,1,0
Test3,2,2
And lastly print this as an HTML table.
So far I have a working solution for summing the first two columns but I don't know how to get it to work to include the third. To outline the entire process, I have an initial PHP script at the start of a web page that logs clicks to a CSV file:
<?PHP
if (isset($_GET['s1'])){
$sub1 = urlencode($_GET['s1']);
$fp1 = fopen ('botlog.csv', 'a+' );
fputcsv ( $fp1, array ( $sub1, '1', '0' ), ",", '"' );
fclose ( $fp1 );}
?>
Later I have a second script, loaded in an iFrame with a JS delay, that logs a similar value but to the third column rather than the second:
<?PHP
if (isset($_GET['sub1'])){
$sub2 = urlencode($_GET['sub1']);
$fp2 = fopen ('botlog.csv', 'a+' );
fputcsv ( $fp2, array ( $sub2, '0', '1' ), ",", '"' );
fclose ( $fp2 );}
?>
Then, I have the following to a) aggregate rows for the 2nd column value (haven't figured out how to do the third too) and put into an array, b) dump it all as a table:
<?php
$array = array_map('str_getcsv', file('botlog.csv'));
$inputfile = 'botlog.csv';
$inputHandle = fopen($inputfile, "r");
$sumArray = array();
while (($dataRow = fgetcsv($inputHandle, 1000, ",")) !== FALSE) {
$subid = $dataRow[0];
$extra1 = $dataRow[2];
if (!isset($sumArray[$subid])) {
$sumArray[$subid] = 0;
}
$sumArray[$subid] += $extra1;
}
var_dump($sumArray); //test sum works
function build_table($sumArray){
// start table
$html = '<table>';
// header row
$html .= '<tr>';
$header=array("SUBID"=>"1","Initial Clicks"=>"2","Secondary Clicks"=>"3", "Percentage"=>"4");
foreach($header as $key=>$value){
$html .= '<th>' . $key . '</th>';
}
$html .= '</tr>';
// data rows
foreach( $sumArray as $key=>$value){
$html .= '<tr>';
foreach($value as $key2=>$value2){
$html .= '<td>' . $value2 . '</td>';
}
$html .= '</tr>';
}
// finish table and return it
$html .= '</table>';
return $html;
}
echo build_table($array);
?>
The initial code works in that it makes an array with the column 2 values summed. Woot! However, I then try to use the HTML table print out on this sumArray, but it just displays the original content (i.e. not that generated from the while function.
So, goals:
Modify initial code block to create a $sumArray that merges all identical column 1 rows but adds their column 2 and 3 values.
Print this out in a nifty table with a 4th spare column.
Help much appreciated!
EDIT: This is the final working code I used:
<?php
if (file_exists('botlog.csv')) {
$array = array_map('str_getcsv', file('botlog.csv'));
$inputfile = 'botlog.csv';
$inputHandle = fopen($inputfile, "r");
$sumArray = array();
while (($dataRow = fgetcsv($inputHandle, 1000, ",")) !== FALSE) {
$subid = $dataRow[0];
if (!isset($sumArray[$subid])) {
$sumArray[$subid] = array_fill(0, count($dataRow)-1, 0);
}
for ($i = 1; $i < count($dataRow); $i++) {
$sumArray[$subid][$i-1] += $dataRow[$i];
}}
arsort($sumArray);
$table = $sumArray;
echo '<table>';
echo "<thead><td><span>Subid</span></td><td><span>Initial Clicks</span></td><td><span>Secondary Clicks</span></td><td><span>Percentage</span></td></thead>";
foreach ($table as $subids => $values)
{
echo "<tr><td>".$subids."\n";
echo "<td>" . $values['0'] . "</td>";
echo "<td>" . $values['1'] . "</td>";
echo "<td>Final column contents</td>";
}
echo "</table>";
}
else{ echo "Botlog.csv file was not found in current directory";}
?>
Make $sumArray a 2-dimensional array. The key of the first dimension is the first column of the CSV, and the second dimension is the sums of the remaining columns.
while (($dataRow = fgetcsv($inputHandle, 1000, ",")) !== FALSE) {
$subid = $dataRow[0];
if (!isset($sumArray[$subid])) {
$sumArray[$subid] = array_fill(0, count($dataRow)-1, 0);
}
for ($i = 1; $i < count($dataRow); $i++) {
$sumArray[$subid][$i-1] += $dataRow[$i];
}

PHP file and array

I am totally lost here, I made a text file with names in it. I would like to assign a array to each name and open it into a php file for displaying on a webpage so I can change things, I just cannot for the life of me figure this out.
$lines = file('responders.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line_num => $line)
{
print "<input type='checkbox' name='responders[]' value='" . $line_num . "' >" . $line . " " . $line_num . "<br />\n";
}
My text file just has names example
Jon
Jim
Tim
Tom
Jerry
I would like to assign an array somehow to basically say
4 Jon
5 Jim
17 Tim
47 Tom
52 Jerry
Without having to use a bunch of white space per line. Is it at all possible? Thanks.
In the end I would like to read my mysql database find out whos all listed and put a check mark next to people who is in the mysql field. I used Implode for that if that helps anybody.
If combine wouldn't work for you you could just explicitly declare the array k/v.
$lines = file('responders.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$nameArray = array();
$i = 0;
foreach ($lines as $line)
{
echo $i . " > " . $line . "\n";
$nameArray[i] = $line;
$i++;
}
There is a more easy way to achieve this:
$content = file_get_contents("responders.txt");
if(strlen($content) > 0) {
$myData= explode(" ", $content);
if(count($myData) > 0) {
$c = 1;
foreach($myData as $value) {
echo $value . " -> ";
if($c % 2 == 0) {
echo "<br />";
}
$c++;
}
}
}

Create a comma-separated string from a single column of an array of objects

I'm using a foreach loop to echo out some values from my database, I need to strip the last comma from the last loop if that makes sense.
My loop is just simple, as below
foreach($results as $result){
echo $result->name.',';
}
Which echos out
result,result,result,result,
I just need to kill that pesky last comma.
Better:
$resultstr = array();
foreach ($results as $result) {
$resultstr[] = $result->name;
}
echo implode(",",$resultstr);
1. Concat to string but add | before
$s = '';
foreach ($results as $result) {
if ($s) $s .= '|';
$s .= $result->name;
}
echo $s;
2. Echo | only if not last item
$s = '';
$n = count($results);
foreach ($results as $i => $result) {
$s .= $result->name;
if (($i+1) != $n) $s .= '|';
}
echo $s;
3. Load to array and then implode
$s = array();
foreach ($results as $result) {
$s[] = $result->name;
}
echo implode('|', $s);
4. Concat to string then cut last | (or rtrim it)
$s = '';
foreach ($results as $result) {
$s .= $result->name . '|';
}
echo substr($s, 0, -1); # or # echo rtrim($s, '|');
5. Concat string using array_map()
echo implode('|', array_map(function($result) { return $result->name; }, $results));
$result_names = '';
foreach($results as $result){
$result_names .= $result->name.',';
}
echo rtrim($result_names, ',');
I've been having the same issue with this similar problem recently. I fixed it by using an increment variable $i, initializing it to 0, then having it increment inside the foreach loop. Within that loop place an if, else, with the echo statement including a comma if the $i counter is less than the sizeof() operator of your array/variable.
I don't know if this would fix your issue per se, but it helped me with mine. I realize this question is years-old, but hopefully this will help someone else. I'm fairly new to PHP so I didn't quite understand a lot of the Answers that were given before me, though they were quite insightful, particularly the implode one.
$i=0;
foreach ($results as $result) {
$i++;
if(sizeof($results) > $i) {
echo $result . ", ";
} else {
echo $result;
}
}
In modern PHP, array_column() will allow you to isolate a column of data within an array of objects.
Code: (Demo)
$results = [
(object)['name' => 'A'],
(object)['name' => 'B'],
(object)['name' => 'C']
];
echo implode(',', array_column($results, 'name'));
Output:
A,B,C
That said, since you are iterating a result set, then you may be better served by calling a CONCAT() function in your sql, so that the values are already joined in the single value result set.
If you are processing a collection in Laravel, you can pluck() and implode():
$collection->pluck('name')->implode(',')
$arraySize = count($results);
for($i=0; $i<$arraySize; $i++)
{
$comma = ($i<$arraySize) ? ", " : "";
echo $results[$i]->name.$comma;
}
Not as pretty, but also works:
$first=true;
foreach($results as $result){
if(!$first) { echo ', '; }
$first=false;
echo $result->name;
}
Another smart way is:
foreach($results as $result){
echo ($passed ? ',' : '') . $result->name;
$passed = true;
}
In this case at first loop $passed is NULL and , doesn't print.
I know this is an old thread, but this came up recently and I thought I'd share my alternate, cleaner way of dealing with it, using next().
$array = array("A thing", "A whatsit", "eighty flange oscillators");
foreach( $array as $value ){
echo $value;
$nxt = next($array);
if($nxt) echo ", "; // commas between each item in the list
else echo ". And that's it."; // no comma after the last item.
}
// outputs:
// A thing, A whatsit, eighty flange oscillators. And that's it.
play with it here
I have to do this alot because I'm always trying to feed numbers in to jplot, I find its easier to put the comma in the front of the loop like so:
foreach($arrayitem as $k){ $string = $string.",".$k;
}
and then chop off the first character (the comma) using substr, it helps if you know a guestimate of long your string will be, I'm not sure what the limit on substr max character is.
echo substr($a,1,10000000);
hope this helps.
$a[0] = 'John Doe';
$a[1] = 'Jason statham';
$a[2] = 'Thomas Anderson';
$size = count($a);
foreach($a as $key=>$name){
$result .= $name;
if($size > $key+1) $result .=', ';
}
echo $result;
<?php
$return = array(any array)
$len = count($return);
$str = '';
$i = 1;
foreach($return as $key=>$value)
{
$str .= '<a href='.$value['cat_url'].'>'.$value['cat_title'].'</a>';
if($len > $i)
{
$str .= ',';
$i = $i+1;
}
}
echo $str;
?>
<?php
$i = 1;
$count = count( $results );
foreach( $results as $result ) {
echo $result->name;
if ( $i < $count ) echo ", ";
++$i;
}
?>
This is what I normally do, add a comma before the item rather than after, while ignoring the first loop.
$i = 0;
$string = '';
foreach($array as $item){
$string .= ($i++ ? ',' : '').$item;
}
First get all the output by using output buffering. Then, trim the comma and display it. So, do it like this:
ob_start();
foreach($results as $result)
{
echo $result->name.',';
}
$output = ob_get_clean();
echo rtrim($output, ',');
The output buffering method helps if the inside loop is very big (and OP is posting here just for brevity), then using OB is easier without changing the internals of the loop.

Categories