Format text to fit in columns in Excel - php

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)

Related

if statement not returning true even though it should

I'm trying to write a simple if statement that should be returning true but is instead returning false. The issue I'm having is that for several items on my list $dataPeriod should be returning true matching '202265' I've tried converting it to a string thinking it didn't like that I was comparing a string to an int and that didn't seem to help.
I'm importing the data from this CSV file - https://www.harpercollege.edu/_resources/php/openclasslistweb.csv
<?php
$next = 0;
$file_to_read = fopen('openclasslistweb.csv', 'r');
if($file_to_read !== FALSE){
echo "<table class = 'open-list-table'>\n";
while(($data = fgetcsv($file_to_read, ',')) !== FALSE){
for($i = 0; $i < count($data); $i++) {
if ($i == 0){
$dataCourse = $data[$i];
}
if ($i == 1){
$dataCRN = $data[$i];
}
if ($i == 2){
$dataTitle = $data[$i];
}
if ($i == 3){
$dataMethod = $data[$i];
}
if ($i == 4){
$dataInstructor = $data[$i];
}
if ($i == 5){
$dataStartDate = $data[$i];
}
if ($i == 6){
$dataEndDate = $data[$i];
}
if ($i == 7){
$dataMonday = $data[$i];
}
if ($i == 8){
$dataTuesday = $data[$i];
}
if ($i == 9){
$dataWednesday = $data[$i];
}
if ($i == 10){
$dataThursday = $data[$i];
}
if ($i == 11){
$dataFriday = $data[$i];
}
if ($i == 12){
$dataSaturday = $data[$i];
}
if ($i == 13){
$dataSunday = $data[$i];
}
if ($i == 14){
$dataStartTime = $data[$i];
}
if ($i == 15){
$dataEndTime = $data[$i];
}
if ($i == 16){
$dataRoom = $data[$i];
}
if ($i == 17){
$dataBuilding = $data[$i];
}
if ($i == 18){
$dataSchedule = $data[$i];
}
if ($i == 19){
$dataDesc = $data[$i];
}
if ($i == 20){
$dataPeriod = $data[$i];
}
}
if (strpos($dataPeriod, "202265") !== false) {
if ($next == 0){
echo "<tr class='open-list-header'>";
}
else {
echo "<tr>";
}
echo "<td>" . $dataCourse . "</td>" . "<td>" . $dataCRN . "</td>" . "<td>" . $dataTitle . "</td>" . "<td>" . $dataMethod . "</td>" . "<td>" . $dataInstructor . "</td>" . "<td>" . $dataStartDate . "</td>" . "<td>" . $dataEndDate . "</td>" . "<td>" . $dataMonday . "</td>" . "<td>" . $dataTuesday . "</td>" . "<td>" . $dataWednesday . "</td>" . "<td>" . $dataThursday . "</td>" . "<td>" . $dataFriday . "</td>" . "<td>" . $dataSaturday . "</td>" . "<td>" . $dataSunday . "</td>" . "<td>" . $dataStartTime . "</td>" . "<td>" . $dataEndTime . "</td>" . "<td>" . $dataRoom . "</td>" . "<td>" . $dataBuilding . "</td>" . "<td>" . $dataSchedule . "</td>" . "<td>" . $dataDesc . "</td>" . "<td>" . $dataPeriod . "<td>";
echo "</tr>\n";
$next = $next + 1;
}
}
echo "</table>\n";
fclose($file_to_read);
}
?>
Your CSV has a lot of invisible characters or encoded characters, so some of your values aren't what you expect. I was able to get all of the unique values for $data[20], and with json_encode it shows this:
{
"0":"\u0000A\u0000c\u0000a\u0000d\u0000e\u0000m\u0000i\u0000c\u0000 \u0000P\u0000e\u0000r\u0000i\u0000o\u0000d\u0000",
"1":"\u00002\u00000\u00002\u00002\u00006\u00005\u0000",
"16":"\u0000O\u0000n\u0000l\u0000i\u0000n\u0000e\u0000 \u0000A\u0000N\u0000Y\u0000T\u0000I\u0000M\u0000E\u0000 \u0000(\u0000A\u0000s\u0000y\u0000n\u0000c\u0000h\u0000r\u0000o\u0000n\u0000o\u0000u\u0000s\u0000)\u0000",
"180":"\u00002\u00000\u00002\u00002\u00009\u00005\u0000",
"982":"\u00002\u00000\u00002\u00003\u00003\u00005\u0000",
"2104":"\u0000L\u0000L\u00001\u0000"
}

How to get loop JSON all of Array (from URL) into a HTML Table with php

I am trying to get the EquipmentList from the Vehicles list in the JSON URL: JSON link
Look at documentation here: Link to documentation
I am trying to add the EquipmentList so that it appears in the table like the images... Just for now at least...
My code so far:
<?php
$url = 'https://gw.bilinfo.net/listingapi/api/export';
// provide your username and password here
$auth = base64_encode("demo:ocfB6XzF73");
// create HTTP context with basic auth
$context = stream_context_create([
'http' => ['header' => "Authorization: Basic $auth"]
]);
// query for data
$data = file_get_contents($url, false, $context);
// $escaped = json_encode($data);
$escaped = json_decode($data); //, JSON_FORCE_OBJECT
/*Initializing temp variable to design table dynamically*/
$temp = "<table>";
/*Defining table Column headers depending upon JSON records*/
$temp .= "<tr>";
$temp .= "<th>Bil</th>";
$temp .= "<th>Model</th>";
$temp .= "<th>Motor</th>";
$temp .= "<th>Drivmiddel</th>";
$temp .= "<th>Udstyr</th>";
$temp .= "<th>Billeder</th>";
$temp .= "</tr>";
/*Dynamically generating rows & columns*/
foreach ($escaped->Vehicles as $vehicle) {
$temp .= "<tr>";
$temp .= "<td>" . $vehicle->Make . "</td>";
$temp .= "<td>" . $vehicle->Model . "</td>";
$temp .= "<td>" . $vehicle->Motor . "</td>";
$temp .= "<td>" . $vehicle->Propellant . "</td>";
for ($e = 0; $e < $vehicle->EquipmentList; $e++) {
$temp .= "<td>" . $vehicle->EquipmentList[0] . "</td>";
}
for ($p = 0; $p < $vehicle->PictureCount; $p++) {
$temp .= "<td><img src='" . $vehicle->Pictures[0] . "'></td>";
}
}
$temp .= "</tr>";
/*End tag of table*/
$temp .= "</table>";
/*Printing temp variable which holds table*/
echo $temp;
//echo $data;
?>
"EquipmentList": [ "ABSBrakes", "Alarm", "AlloyRims", "AntiSpin", "AutomaticGear", "RemoteCentralLocking", "PoweredWindows", "PoweredMirrorsHeated", "CruiseControl", "InfoCenter", "AutomaticClimateControl", "TripComputer", "Navigation", "GearShiftStearingWheel", "ServiceOK", "Immobilizer", "SeatHeater", "XenonLight" ]
does $EquipmentList correctly describe the values inside the variable?
Perhaps $EquipmentItem is more correct?
if so, it will return an object (json)
for example
{
"name": "Motor 1 A",
"img": "/someimg.jpg"
}
to display an image, you need <img/> tag
foreach($escaped->Vehicles[0]->EquipmentList as $EquipmentItem){
$temp .= "<td>" . "<img src='" . $EquipmentItem->img . "' />" . "</td>";
}
Based on your example, the correct solution may vary, but this should give you idea if the correct question has been answered.
I modified Phillip Zoghbi's code - removed the image part c;) - So in part Phillip is right!
foreach($escaped->Vehicles[0]->EquipmentList as $EquipmentItem){
$temp .= "<td>" . $EquipmentItem . "</td>";
}

How can I make Pagination throw csv file in PHP?

I have a csv file with some data inside.
When User type something in the search bar,it will return the relate data but these results are too much, I want to make a pagination.I don't have any idea, google a lot but can't find a way to do. Please help.
$filename = "Database.csv";
$delimiter = ",";
if (!file_exists($filename) || !is_readable($filename))
return false;
if ($delimiter == ',') {
$csv = array_map('str_getcsv', file($filename));
} else {
$lines = file($filename);
$line_num = count($lines);
$dm = [];
$csv = array_map('str_getcsv', $lines, array_pad($dm, $line_num, $delimiter));
}
array_walk($csv, function (&$row) use ($csv) {
$row = array_combine($csv[0], $row);
});
array_shift($csv);
$total_row_of_csv = count($csv);
$total_row = 0;
for ($i = 0; $i < $total_row_of_csv; $i++) {
if (preg_match("/$value/i", $csv[$i]['Catagory'])) {
echo "<tr>";
echo "<td>" . $csv[$i]['Ref'] . "</td>";
echo "<td>" . $csv[$i]['Catagory'] . "</td>";
echo "<td>" . $csv[$i]['JobTitle'] . "</td>";
echo "<td>" . $csv[$i]['Description'] . "</td>";
echo "<td>" . $csv[$i]['Salary'] . "</td>";
echo "<td>" . $csv[$i]['Nature'] . "</td>";
echo "</tr>";
$total_row++;
}
}
GET : index.php?page=2&search=purchasing
clear the page=1 for a new search
This function is done with get method not post, you can do it as the post by doing appropriately
<?php
// you can make this as post as you want
// i have made this as a get param function
$value = !empty($_GET['search']) ? $_GET['search'] : '';
$filename = "Database.csv";
$delimiter = ",";
if (!file_exists($filename) || !is_readable($filename))
return false;
if ($delimiter == ',') {
$csv = array_map('str_getcsv', file($filename));
} else {
$lines = file($filename);
$line_num = count($lines);
$dm = [];
$csv = array_map('str_getcsv', $lines, array_pad($dm, $line_num, $delimiter));
}
array_walk($csv, function (&$row) use ($csv) {
$row = array_combine($csv[0], $row);
});
array_shift($csv);
$total_row_of_csv = count($csv);
$countForPage = 0;
for ($i = 0; $i < $total_row_of_csv; $i++) {
//var_dump($csv[$i]['Catagory']);die();
// didint get the $value so commented id
if (preg_match("/$value/i", $csv[$i]['Catagory'])) {
$countForPage ++;
}
}
$countForPage;
$numPerPage = 10;
$numCurrPage = !empty($_GET['page']) ? $_GET['page'] : 1;
$numFromCnt = $numPerPage * ($numCurrPage - 1);
$numLastCnt = $numFromCnt + $numPerPage ;
$total_row = 0;
echo "<table>";
for ($i = 0; $i < $total_row_of_csv; $i++) {
//var_dump($csv[$i]['Catagory']);die();
// didint get the $value so commented id
if (preg_match("/$value/i", $csv[$i]['Catagory'])) {
//echo $total_row .">=". $numFromCnt ."&&". $total_row ."<". $numLastCnt; //die();
if($total_row >= $numFromCnt && $total_row < $numLastCnt) {
echo "<tr>";
echo "<td>" . $csv[$i]['Ref'] . "</td>";
echo "<td>" . $csv[$i]['Catagory'] . "</td>";
echo "<td>" . $csv[$i]['JobTitle'] . "</td>";
echo "<td>" . $csv[$i]['Description'] . "</td>";
echo "<td>" . $csv[$i]['Salary'] . "</td>";
echo "<td>" . $csv[$i]['Nature'] . "</td>";
echo "</tr>";
}
$total_row++;
}
}
//echo $total_row;die();
echo "</table>";
$links = generateLinks($countForPage, $numCurrPage, $numPerPage, $value);
echo $links;
function generateLinks($total_row_of_csv, $numCurrPage, $numPerPage, $search){
$pagLink = '';
if($numCurrPage > 1) {
$pagLink .= "<li class='active'><a href='csv_pagination.php?page="
.($numCurrPage-1)."&search=".$search."'>Prev</a></li>";
}
// for ($i=1; $i<=$total_row_of_csv; $i++) {
// if ($i==$numCurrPage) {
// $pagLink .= "<li class='active'><a href='csv_pagination.php?page="
// .$i."'>".$i."</a></li>";
// } else {
// $pagLink .= "<li><a href='csv_pagination.php?page=".$i."'>
// ".$i."</a></li>";
// }
// }
if($numCurrPage < ($total_row_of_csv/$numPerPage)) {
$pagLink .= "<li class='active'><a href='csv_pagination.php?page="
.($numCurrPage+1)."&search=".$search."'>Next</a></li>";
}
return $pagLink;
}
?>

Creating a html Table based on transposed Joomla data

I'm struggling to create a table made of the joomla database. Currently I'm using the following code:
$query= "SELECT DATUM, A , B ,C, D, E, F, G FROM ".$db->quoteName('#__XYZTABLE'). " WHERE DATUM_ENG>= CURDATE()";
$db->setQuery($query);
$results = $db -> loadObjectList();
echo "<table><tr><th>Name</th><th>Department</th></tr>";
foreach($results as $row){
echo "<tr>"; echo "<td>".$row->last_name."</td>";
echo "<td>".$row->dept."</td>";
echo "</tr>"; }
echo "</table>";
Basically, this code works fine. The result is:
DATUM , A , B ,C, D, E, F, G
xxxx1 ,aa1,bb1,cc1,dd1,ee1,ff1,gg1
xxxx2 ,aa2,bb2,cc2,dd2,ee2,ff2,gg2
....
However, I want to create an html table which transposes the data and shows it like the following form:
xxxx1 , xxxx2, xxxx3 ....
A aa1 , aa2 , aa3
B bb1 , bb2 ,bb3
C cc1 , cc2 ,cc3
D .....
After searching in this forum and Google, I wasn't able to find anything similar. Can someone help me with a specific code?
Using some php array functions, you may take this:
$object = new stdClass();
// create some test values
$object->DATUM = '2016120';
$object->A = 'aa';
$object->B = 'bb';
$object->C = 'cc';
$object->D = 'dd';
$object->E = 'ee';
$object->F = 'ff';
$object->G = 'gg';
for ($i = 1; $i < 10; $i++){
$vars = get_object_vars($object);
$obj = new stdClass;
foreach ($vars as $key=>$var){
$obj->$key = $var.$i;
}
$results[] = $obj;
}
// end of creating test values
echo "<table><tr><th>DATUM</th><th>A</th><th>B</th><th>C</th><th>D</th></tr>";
foreach ( $results as $row ) {
echo "<tr>";
echo "<td>" . $row->DATUM . "</td>";
echo "<td>" . $row->A . "</td>";
echo "<td>" . $row->B . "</td>";
echo "<td>" . $row->C . "</td>";
echo "<td>" . $row->D . "</td>";
echo "<td>" . $row->E . "</td>";
echo "<td>" . $row->F . "</td>";
echo "<td>" . $row->G . "</td>";
echo "</tr>";
}
echo "</table>";
echo '<h3>New Variant</h3>';
echo '<table>';
$elements = count($results);
foreach (get_object_vars($results[0]) as $key=>$var){
echo '<tr>';
$tag = ($key === 'DATUM') ? 'th>' : 'td>';
echo '<'.$tag . $key .'</'.$tag;
for ($i = 0; $i < $elements; $i++){
echo '<'.$tag . $results[$i]->$key.'</'.$tag;
}
echo '</tr>';
}
echo '</table>';`

PHP read file match if statement

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>

Categories