PHP file and array - php

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++;
}
}
}

Related

read row and columns of text file in 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'));

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 CSV Output - How to add two rows?

Hellos!
Alessandro Minoccheri already helped me alot with this code, but I've got one more problem. The CSV file is a output file from powershell (get-aduser) - it is comma seperated.
As first this is the csv content:
#TYPE Selected.Microsoft.ActiveDirectory.Management.ADUser
name,"officephone"
firstname, lastname,"+49 1234 555 134"
firstname, lastname,"+49 1234 555 242"
firstname, lastname,"+49 1234 555 338"
firstname, lastname,"+49 1234 555 149"
And this is the code for the moment:
$lineCount = 0;
while (($line = fgetcsv($f)) !== false) {
if ($lineCount > 1) {
echo "<tr class='departmenttext'>";
foreach ($line as $key => $cell) {
if ($key == 1) {
$cell = substr($cell, -3);
echo '';
}
echo "<td>" . htmlspecialchars($cell) . "</td>";
if ($key == 1) {
echo "</tr>\n";
}
}
echo "</tr>\n";
}
$lineCount = $lineCount + 1;
}
it displays a CSV file in one row. Means
Name1 Phone1
Name2 Phone2
Name3 Phone3
Name4 Phone4
But as it is sometimes very long I would be in need of the following:
Name1 Phone1 Name5 Phone5
Name2 Phone2 Name6 Phone6
Name3 Phone3 Name7 Phone7
Name4 Phone4
But as I just got one export function "htmlspecialchars($cell) I don't know how to separate it?
It's difficult to wrap the file like you want, but the alternative is to put entries side by side...
$lineCount = 0;
fgetcsv($f);
fgetcsv($f);
while (($line = fgetcsv($f)) !== false) {
if ( count($line)<2 ) {
break;
}
if ($lineCount % 2 == 0) {
echo "<tr class='departmenttext'>";
}
echo "<td>" . htmlspecialchars($line[0].','.$line[1]) . "</td>";
echo "<td>" . htmlspecialchars(substr($line[2],-3)) . "</td>";
if ($lineCount % 2 == 1) {
echo "</tr>\n";
}
$lineCount = $lineCount + 1;
}
if ($lineCount % 2 == 1) {
echo "</tr>\n";
}
First of all you have to decide that how much line you want in one bunch. and according to that number, You need to start a new raw in loop.
for example, if you want to show up to 10 line in one bunch, like
you need something like
if($key%10 == 0){
echo "</tr><tr class='departmenttext'>";
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
You can do something like this way
if($key%count($line) == 0){
echo "</tr><tr class='departmenttext'>";
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
Here I have divided it by total number of line so that it can be calculate 50% of your line.

PHP Displaying CSV file, Skip the first row

I'm trying to display the CSV file data, which is inside of the gz file.
My code is:
$file = file("compress.zlib://".$filePath);
foreach($file as $line){
list($lid,$lname,$lrevenue,$ctr) = explode(",", $line);
print $lid ." | ". $lname ." | ". $lrevenue ." | ". $ctr . "\n";
}
This code works but I don't know how to skip displaying the first row from it.
Thanks in advance.
$file = file("compress.zlib://".$filePath);
unset($file[0]);
foreach($file as $line){
list($lid,$lname,$lrevenue,$ctr) = explode(",", $line);
print $lid ." | ". $lname ." | ". $lrevenue ." | ". $ctr . "\n";
}
$file = file("compress.zlib://".$filePath);
$i=0;
foreach($file as $line){
if($i == 0) continue;
list($lid,$lname,$lrevenue,$ctr) = explode(",", $line);
print $lid ." | ". $lname ." | ". $lrevenue ." | ". $ctr . "\n";
$i++;
}

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>';

Categories