PHP read file match if statement - php

everyone I have the following file and I want to show lines that match on if condition and pass the other.
I have this TXT file:
Doc. number|Date|Price|Description|Name
100|11/11/2015|99|Test 1|Alex
101|11/11/2015|120|Test 2
102|11/11/2015|100|Test 3|John
102|11/11/2015|140||
103|11/11/2015|110|Test 4|
And this is my PHP code:
$file_handle = fopen("file.txt", "rb");
$i = 0;
echo "<table border='1'>";
echo "<tr><th>Doc. number</th><th>Date</th><th>Price</th><th>Description</th><th>Name</th></tr>";
while (!feof($file_handle)) {
$line_of_text = fgets($file_handle);
$parts = explode('|', $line_of_text);
if($i > 1) { // Pass the first line
echo "<tr>";
echo "<td>" . $parts[0] . "</td>"; // Doc. number
echo "<td>" . $parts[1] . "</td>"; // Date
echo "<td>" . $parts[2] . "</td>"; // Price
echo "<td>" . $parts[3] . "</td>"; // Description
echo "<td>" . $parts[4] . "</td>"; // Name
echo "</tr>";
}
$i++;
}
fclose($file_handle);
echo "</table>"
How I can check if there are no "Description" and/or "Name" in table and pass this line. I want to show(get) only line that match on if condition.
I will be very grateful if someone have idea. Thanks in advance.

As simple as
$file_handle = fopen("file.txt", "rb");
$i = 0;
echo "<table border='1'>";
echo "<tr><th>Doc. number</th><th>Date</th><th>Price</th><th>Description</th><th>Name</th></tr>";
while (!feof($file_handle)) {
$line_of_text = fgets($file_handle);
$parts = explode('|', $line_of_text);
if($i > 1 && !empty($parts[3]) && !empty($parts[4])) { // Pass the first line and lines without description / name
echo "<tr>";
echo "<td>" . $parts[0] . "</td>"; // Doc. number
echo "<td>" . $parts[1] . "</td>"; // Date
echo "<td>" . $parts[2] . "</td>"; // Price
echo "<td>" . $parts[3] . "</td>"; // Description
echo "<td>" . $parts[4] . "</td>"; // Name
echo "</tr>";
}
$i++;
}
fclose($file_handle);
echo "</table>"

Only print table row if we have name and description:
if($i > 1 && $parts[3] && $parts[4]) {

You can put condition before echo statement and if it will be false just skip "echo";
if (count($parts) === 5) {
$error = 0;
foreach ($parts as $part) {
if (empty($part)) error++;
}
if($i > 1 && $error === 0) {
echo "<tr>";
echo "<td>" . $parts[0] . "</td>"; // Doc. number
echo "<td>" . $parts[1] . "</td>"; // Date
echo "<td>" . $parts[2] . "</td>"; // Price
echo "<td>" . $parts[3] . "</td>"; // Description
echo "<td>" . $parts[4] . "</td>"; // Name
echo "</tr>";
}
}

I've a solution that can help you.
But why I think you need just scape the heading line. so I changed if($i > 1) to be if($i >0)
$file_handle = fopen("file.txt", "rb");
$i = 0;
echo "<table border='1'>";
echo "<tr><th>Doc. number</th><th>Date</th><th>Price</th><th>Description</th><th>Name</th></tr>";
while (!feof($file_handle)) {
$line_of_text = fgets($file_handle);
$parts = explode('|', $line_of_text);
if($i > 0) { // Pass the first line
if ( (!empty($parts[3])) && (!empty($parts[4])) ){
echo "<tr>";
echo "<td>" . $parts[0] . "</td>"; // Doc. number
echo "<td>" . $parts[1] . "</td>"; // Date
echo "<td>" . $parts[2] . "</td>"; // Price
echo "<td>" . $parts[3] . "</td>"; // Description
echo "<td>" . $parts[4] . "</td>"; // Name
echo "</tr>";
}
}
$i++;
}
fclose($file_handle);
echo "</table>"

Your file has a CSV structure, pipe delimited.
So parse it as a CSV.
Note the using of array_shift to get the header of the CSV and passing the delimiter parameter to fgetcsv.
Also consider using implode instead explicitly passing each member of the array between td tags.
Here's an example using two functions, one for parsing the CSV and returning the data,
and another one for displaying the data and doing the validation.
function getData($file){
$rows = array();
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, null, "|")) !== FALSE) {
$rows[] = $data;
}
fclose($handle);
}
return $rows;
}
function displayData($rows){
$header = array_shift($rows);
$output = '<table border="1">' . PHP_EOL;
$output .= '<tr><th>' . implode('</th><th>',$header) . '</th></tr>' . PHP_EOL;
foreach($rows as $row){
if (isset($row[3]) and isset($row[4]) and $row[3]!='' and $row[4]!=''){
$output .= '<tr><td>' . implode('</td><td>',$row) . '</td></tr>' . PHP_EOL;
}
}
$output .= '</table>';
return $output;
}
$rows = getData("pipe.txt");
print displayData($rows);
This will output the following
<table border="1">
<tr><th>Doc. number</th><th>Date</th><th>Price</th><th>Description</th><th>Name</th></tr>
<tr><td>100</td><td>11/11/2015</td><td>99</td><td>Test 1</td><td>Alex</td></tr>
<tr><td>102</td><td>11/11/2015</td><td>100</td><td>Test 3</td><td>John</td></tr>
</table>

Related

Using two array expressions in single forEach loop

If I use two array expressions with two values, I do not get an error but I also get absolutely no output:
NOT WORKING:
<?php foreach ($zones as $zone) {
$body = $zone->get_body();
$domain_name = $zone->get_domain_name();
$name = $zone->get_name();
foreach ($domains as $domain) {
$status = $domain->get_status();
if (strstr($body, $ip)) {
echo "<tr>";
echo "<td>" . $domain_name . "</td>";
echo "<td>" . $status . "</td>";
echo "<td>" . $body . "</td>";
echo "</tr>";
$count++;
}
}
}
So I need to be able to target the $status variable also which uses $domain instead of $zones
When I use the below code for only zones, everything works fine and I get data that outputs.
WORKING:
<?php foreach ($zones as $zone) {
$body = $zone->get_body();
$domain_name = $zone->get_domain_name();
$name = $zone->get_name();
if (strstr($body, $ip)) {
echo "<tr>";
echo "<td>" . $domain_name . "</td>";
echo "<td>" . $name . "</td>";
echo "<td>" . $body . "</td>";
echo "</tr>";
$count++;
}
}

PHP display image based on positive or negative number

I need to display:
/images/image1.jmp if the number is positive
or
/images/image2.jpg if the number is negative
or
/images/image3 if the number is 0.
$stmt = sqlsrv_query($conn,$sql);
echo "<table border='1'><tr><th>Offense</th><th>Previous Date Range</th><th>Current Date Range</th><th>Difference</th><th>Percentage Difference</><th>Up or down image in this column</></tr>";
while( $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC) )
{
echo "<tr>";
echo "<td>" . $row['Offense']. "</td>";
echo "<td>" . $row['PreviousDateRange']."</td>";
echo "<td>" . $row['DateRange']."</td>";
echo "<td>" . $row['difference1']."</td>";
echo "<td>" . $row['percentchange']."</td>";
echo "<td>" . $row['']. "</td>";
}
echo "</table>";
?>
I found this code and have tried different ways if incorporating it in the echo "<td>" . $row['']. "</td> but not having any luck.
I get the code but can not manipulate it to fit what it needs to do. I'm sure it's a simple solution. Just frustrated.
switch ($myNumber) {
case 0:
echo "Zero is not a valid value.";
break;
case $myNumber < 0:
echo "Negative numbers are not allowed.";
break;
default:
echo "Great! Ready to make calculations.";
break;
}
Thanks for the help guys. Got the answer that worked.
I think this is a more readable solution.
I use an array to hold the links and use a calculation to see if it is negative or positive.
$img = ["-1" => "/images/image2.jpg",
"0" => "/images/image3.jpg",
"1" => "/images/image1.jpg"];
$number = 0;
Echo ($number == 0 ? $img[$number] : $img[$number/abs($number)]);
https://3v4l.org/JstZl
If the number is positive the calculation will be 15/15 => 1.
If the number is negative -10/10 => -1.
Edit:
$stmt = sqlsrv_query($conn,$sql);
echo "<table border='1'><tr><th>Offense</th><th>Previous Date Range</th><th>Current Date Range</th><th>Difference</th><th>Percentage Difference</><th>Up or down image in this column</></tr>";
$img = ["-1" => "/images/image2.jpg",
"0" => "/images/image3.jpg",
"1" => "/images/image1.jpg"];
while( $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC) )
{
echo "<tr>";
echo "<td>" . $row['Offense']. "</td>";
echo "<td>" . $row['PreviousDateRange']."</td>";
echo "<td>" . $row['DateRange']."</td>";
echo "<td>" . $row['difference1']."</td>";
echo "<td>" . $row['percentchange']."</td>";
Echo '<td><img src="' . ($row['percentchange'] == 0 ? $img[$row['percentchange']] : $img[$row['percentchange']/abs($row['percentchange'])]) . '"></td>';
}
echo "</table>";
You didn't show us where $myNumber comes from so if the variable name is different just modify it in the code below.
echo '<td>/images/image' . ($myNumber == 0 ? '3' : ($myNumber >= 1 ? '1' : '2')) . '.jpg</td>';
Try:
if($myNumber < 0) {
//show /images/image2.jpg
}
if($myNumber == 0) {
//show /images/image3
}
if($myNumber > 0) {
//show /images/image1.jmp
}
In your code:
while( $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC) )
{
echo "<tr>";
echo "<td>" . $row['Offense']. "</td>";
echo "<td>" . $row['PreviousDateRange']."</td>";
echo "<td>" . $row['DateRange']."</td>";
echo "<td>" . $row['difference1']."</td>";
echo "<td>" . $row['percentchange']."</td>";
echo "<td>";
if($row['percentchange'] < 0) {
//show /images/image2.jpg
}
if($row['percentchange'] == 0) {
//show /images/image3
}
if($row['percentchange'] > 0) {
//show /images/image1.jmp
}
echo "</td>";
}
This is assuming, based off of your other comments, that $row['percentchange'] is the number in particular that you care about checking against.

PHP CSV dynamic table want to make all entries in fifth column links

I have a dynamic table created from my PHP script. The information is sourced from a CSV file. I would like everything in the fifth column to be a link to another page. So that would be every array index/key 4 is a link. Unsure on how i would modify the code below to achieve this?
echo "<html><body><table>\n\n";
echo "<tr><td>First</td><td>Last</td><td>Email<td>Address</td
<td>File</td></tr>";
$f = fopen("filelog.csv", "r");
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
foreach ($line as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "</tr>\n";
}
fclose($f);
echo "\n</table></body></html>";
Add a counter to your loop and look for every 5th iteration.
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
$i = 0;
foreach ($line as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
$i++;
if($i % 5 === 0) {
echo "<td>" . yourlinkstuff . "</td>";
}
}
echo "</tr>\n";
}
I am using modulus because it's unclear from your question whether or not there are more than 4 "cells" per "line". If the foreach($line as $cell) always iterates 4 times, you don't need a counter. You could just tag on the 5th column after that loop, like so:
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
foreach ($line as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "<td>" . yourlinkstuff . "</td>";
echo "</tr>\n";
}
You could add a counter and when you reach the 4th element, output a link.
$i = 1;
foreach ($line as $cell) {
if ($i == 4) {
// Create the link.
echo "<td> </td>";
}
else {
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
$i++;
}
Thank you all for your input, I really appreciate it. I have a table that has five columns, "First, Last, Email, Address, File". Everything in the "File" column is a link to that file. So yes in the array starting at index 0 the "File" data will be at index 4. I didn't want an extra column. This is code that ended up doing the job, thank you!!
echo "<html><body><table>\n\n";
echo "<tr><td>First</td><td>Last</td><td>Email<td>Address</td>
<td>File</td></tr>";
$fp = fopen("filelog.csv", "r");
while (($line = fgetcsv($fp)) !== false) {
echo "<tr>";
$i=1;
foreach ($line as $cell) {
if(($i % 5) == 0) {
echo "<td><a href=" . htmlspecialchars($cell) . ">"
.htmlspecialchars($cell) . "</a></td>";
}
else {
echo "<td>" . htmlspecialchars($cell) . "</td>";
$i++;
}
}
echo "</tr>\n";
}
fclose($fp);
echo "\n</table></body></html>";

Format text to fit in columns in Excel

I have this block of text in an array:
"Stefan Olsson"
"Kungsvägen"
"Skolgatan"
xxxx-xx-xx
0735xxxxxx,
"Pär Davidsson"
"Skolgatan"
"Myntvägen"
xxxx-xx-xx
0709xxxxxx,
I parse this type of content to an CSV-file, for later usage in Excel. However, I want to fromat this text to fit in different columns in excell. So, when I open the CSV-file in Execel, I want the name to be in one column, the address in the column besides etcetc. How can I accomplish this? Should I use PHPExcel? Or could it be done with plain old PHP?
Here is my PHP-code
$gatunamn = $_POST['gata'];
$ort = $_POST['omrade'];
$csv_data = array();
$newSpider->fetchPage($gatunamn, $ort, $offset=0);
$obj = json_decode($newSpider->html);
echo "<div id='rightcontent'><table id='one-column-emphasis'>";
echo "<th><input type='checkbox' name='csv_all' id='csv_all'></th><th>Namn</th><th>Adress</th><th>Adress2</th><th>Adress3</th><th>Personnummer</th><th>Telefonnummer</th><th>Telefonnummer2</th>";
$antal_sidor = round($obj->search->wp->totalHits / $obj->search->wp->pageSize);
echo "<td></td>";
foreach($obj->search->wp->features as $fish) //Loopar ut 50st (pageSize)
{
echo "<tr>";
echo "<td><input type='checkbox' value='csv' class='csv'></td>";
echo "<td>" . $fish->name . "</td>";
$csv_data[] .= utf8_decode($fish->name);
foreach($fish->addresses as $ad)
{
echo "<td>" . $ad->label . " " . $ad->postcode . " " . $ad->area . "</td>";
$csv_data[] .= utf8_decode($ad->label . " " . $ad->postcode . " " . $ad->area);
}
if(!empty($fish->dateOfBirth))
{
$convert_date = substr($fish->dateOfBirth, 0, -3); //Gör om datum från timestamp
echo "<td>" . date("Y-m-d", $convert_date) . "</td>";
$convert_datee = date("Y-m-d", $convert_date);
$csv_data[] .= $convert_datee;
}
if(!empty($fish->phoneNumbers))
{
foreach($fish->phoneNumbers as $ph)
{
echo "<td>" . $ph . "</td>";
$csv_data[] .= $ph . ",";
}
}
echo "</tr>";
}
echo "</table>";
$j = 0;
for($i = 1; $i <= $antal_sidor; $i++)
{
echo "<a href='curl2.php?gatunamn=$gatunamn&ort=$ort&offset=$j'>" . $i . "</a> ";
$j += 100;
}
echo "</div>";
echo "<div id='debug'><pre>";
var_dump($csv_data);
echo "</pre></div>";
}
if(isset($_POST['export']))
{
$fp = fopen("eniroo.csv","w");
foreach(explode(",", implode("\n",$csv_data)) as $rad) {
fputcsv($fp, array(implode(',', str_getcsv($rad, "\n"))));
}
echo "<div id='csv_info'>";
echo "<a href='eniro.csv'>Hämta CSV-fil</a>";
echo "</div>";
}
// Restructure the original array into rows
$myDataArray = array_chunk($myDataArray, 5);
// Then write to CSV
$fp = fopen('file.csv', 'w');
foreach($myDataArray as $dataRow) {
fputcsv($fh, $dataRow);
}
fclose($fh)

How to get td data from a table in PHP

I am currently stuck at this problem right now where I don't seem to have any idea how to implement this. I have this table which is populated from a csv file in php and I want to get the data logged in order to calculate the daylight hours.
How can I get the data from the td "dateLogged", I did that in jquery before using children but I do not seem to be able to do that in php
//print out uploaded file.csv
echo "<html><body><table BORDER=1>\n\n";
echo " <tr><th>AvgCrown</th><th>MinCrown</th><th>MaxCrown</th><th>dateLogged</th><th>DaylightHours</th></tr>";
$f = fopen("./uploads/" . $_FILES["uploadedfile"]["name"], "r");
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
foreach ($line as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "<td>" . calcDaylight() . "</td>";
echo "<tr>\n";
}
fclose($f);
echo "\n</table></body></html>";
Here is a sample how the table looks like
Any help will be most welcome.
There's no need to parse the HTML if you can just grab the data while you're generating it.
Something like this should be all you need:
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
foreach ($line as $cell) {
// Save the value before you output
$lastColValue = htmlspecialchars($cell);
echo "<td>" . $lastColValue . "</td>";
}
// If you want to store all log dates in an array:
$logDates[] = $lastColValue;
// Or if you want to do something with that value in calcDaylight:
echo "<td>" . calcDaylight( $lastColValue ) . "</td>";
echo "<tr>\n";
}
fclose($f);
Incidentally, if you do find you need to parse the HTML and are only familiar with jQuery, this library may strike your fancy:
http://code.google.com/p/phpquery/
this?
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
foreach ($line as $cell) {
echo "<td>".htmlspecialchars($cell)."</td>";
}
echo "<td>" . calcDaylight( $cell[3] ) . "</td>";
echo "<tr>\n";
}
i might be wrong but 4th column is the field you want, no?

Categories