How to unite 3 files in one table? - php

I have a test script, that generate txt file with answers. And have 2 txt files with the correct answers. I want:
1) Unite all files in one table, like:
<table>
<tr>
<td>№ of question</td>
<td>data from file 1</td>
<td>data from file 2</td>
<td>data from file 3</td>
</tr>
...
</table>
2) I want to replace id in this files on text from DB (MySQL). I have table with question and answers with similar id (like in txt files).
All files have structure like:
1|3
2|4
3|1
where first number - is id of a question, and second is a variant of answer.
I start coding, but don't know how to include data from files:
// Slect from DB
$qsel=mysql_query("SELECT `qid`, `qtext` from `questions` ORDER BY `qid`");
// Open file 1
$key1=fopen("data/test_1_key1.txt", "r");
$k1=explode("/r/n", $key1);
// Open file 2
$key2=fopen("data/test_1_key2.txt", "r");
$k2=explode("/r/n", $key2);
$rtable='<table border="1" cellspacing="0" cellpadding="3">
<tr>
<th width="40%">Q</th>
<th width="20%">A 1</th>
<th width="20%">A 2</th>
<th width="20%">NAME</th>
</tr>';
while($q=mysql_fetch_row($qsel))
{
$rtable.='<tr><td><b>'.$q['1'].'</b></td>';
$rtable.='<td>data from file 1</td>';
$rtable.='<td>data from file 2</td>';
$rtable.='<td></td>';
}
echo '</table>'.$rtable;

I would first fetch the textfiles and convert it into indexed array:
$tmp1 = file('text1.txt');
$data1 = array();
foeach($tmp1 as $line)
{
list($key1, $val1) = explode("|", $line);
$data1[$key1] = $val1;
}
and then, on mysql fetch loop, just use the indexed array:
while($q=mysql_fetch_row($qsel))
{
$rtable.='<tr><td><b>'.$q['1'].'</b></td>';
$rtable.='<td>' . ( isset( $data1[ $q['0'] ] ) ? $data1[ $q['0'] ] : '' ) . '</td>';
$rtable.='<td>data from file 2</td>';
$rtable.='<td></td>';
}

Related

How to write content by calling WriteHtml() function twice at a same file using mpdf library in PHP 7?

I wanna write a table with the records from my database into PDF using mpdf. But when i retrieve the records using while loop my table header takes the effect, the records doing loop as well as table header because the "WriteHtml()" function inside the loop.
I've tried to solve this problem by calling "WriteHtml()" twice, which means to write the table header and content separtely, but the mpdf produces a blank page PDF file.
$html = "<table border='0' width='100%' cellspacing='0'>
<tr>
<th>ID</th>
<th>NAMA</th>
<th>PEKERJAAN</th>
<th>ALAMAT</th>
<th>SUKU</th>
</tr>";
$mpdf->WriteHTML(utf8_decode($html),\Mpdf\HTMLParserMode::DEFAULT_MODE, true, false);
while ($data = mysqli_fetch_array($mysqli_query)) {
$html2 = "<tr>
<td align='center'>".htmlspecialchars($id++)."</td>
<td align='center'>".htmlspecialchars($data['nama'])."</td>
<td align='center'>".htmlspecialchars($data['pekerjaan'])."</td>
<td align='center'>".htmlspecialchars($data['alamat'])."</td>
<td align='center'>".htmlspecialchars($data['suku'])."</td>
</tr>
</table>";
$mpdf->WriteHTML(utf8_decode($html2),\Mpdf\HTMLParserMode::DEFAULT_MODE,false, true);
}
$mpdf->Output();
I expect the content of PDf file output is the table like my index.php like this:
https://photos.smugmug.com/Stackoverflow/i-26sKBgt/0/ed83bc1c/L/expect_output%20-%20Copy-L.png
instead of like this:
https://photos.smugmug.com/Stackoverflow/i-cVszxJW/0/af15bde0/L/unexpect_output%20-%20Copy-L.png
i am sorry i post a link because i am not being able to post image right now

how to write html table in .txt file using php

I want to export datatable records in .txt file and am using doing this with file handling function but when I am trying to create table in txt file it will give me the following output:
by doing this
$fileName = 'filenametxt'.date('Y_m_d_H_i_s').".txt";
$filePath = $upload_path.'/file_folder_txt/';
$fileNameWithPath = $filePath.$fileName;
$txtHeaderData .= '<table id="" class="uk-table uk-table-hover uk- table-striped uk-table-condensed" border="0" cellpadding="5">
<tr>
<th>Location</th>
<th>Filed Name</th>
<th>Length</th>
<th>Description of Fields</th>
</tr>
';
$txtHeaderData .= '</table>';
$handle = fopen($fileNameWithPath, "w");
fwrite($handle, $txtHeaderData);
but the expected output is:
can some please help me that how I can achieve this?
The table you see/want is just a default HTML table, styled by the browser. TXT files only hold text no styling, which your file seems to be doing pretty good.
You could write the output as a CSV file, which would allow people to view the file in Excel (basically on big table)
$fp = fopen('output.csv', 'w');
$fields = array("location", "field name", "length", "description");
fputcsv($fp, $fields);
fputcsv($fp, $fields);
I haven't had time to test this code, but according to the docs it should work.
You could also write your own txt table, tho I do not recommend this since some columns will always be larger than others.
$csvHeaderData = "----------------------------------------" . PHP_EOL;
$csvHeaderData .= "| Location | Field name | Length | Description |" . PHP_EOL;
$csvHeaderData .= "---------------------------------------";

Bootstrap TableExport decimal issue

I have a bootstrap table displaying employee data, including the payroll ID which have the given format: 1606.xxxx
Here's what my table looks like :
<table id="table_search"
data-toggle="table"
data-search="true"
data-show-refresh="true"
data-show-toggle="true"
data-show-columns="true"
data-show-export="true"
data-minimum-count-columns="2"
data-show-pagination-switch="true"
data-pagination="true"
data-page-list="[10, 25, 50, 100, ALL]"
data-show-footer="false"
data-export-data-type="all"
data-export-types="['excel']">
<thead>
<tr>
<th data-field="id">ID</th>
<th data-field="payroll_id" >Payroll ID</th>
<th data-field="nama_karyawan">Employee Name</th>
<th data-field="level">Level</th>
<th data-field="grade">Grade</th>
<th data-field="title">Title</th>
<th data-field="lokasi">Location</th>
<th data-field="cost_sales">Cost Sales</th>
<th data-field="dept">Department</th>
<th data-field="div">Division</th>
<th data-field="dir">Directorat</th>
<th data-field="active_period">Active Period</th>
</tr>
</thead>
</table>
The table displays it correctly, however when I export it into excel using TableExport plugin it goes like this
exported results
As you can see, somehow the plugin treats it as a number with decimal, which is exactly what I am avoiding. I've tried commenting the parseNumber function which might be the cause in the tableExport js file, however the results always comes out the same
What am I doing wrong ?
PS: I don't want formatting after the file is exported, I want it to export the data as is.
You could use
...
<td data-tableexport-msonumberformat="\#">123.450</td>
...
With this the tableExport.js will use mso-number-format: "\#" as TDstyle while creating the HTMLExcel export. This results in formatting the cell as Text.
Example:
http://jsfiddle.net/uqtubq5c/1/
You could also use
...
<td data-tableexport-msonumberformat="0.000">123.450</td>
...
This leads to the number format 0.000 in Excel. So the cell content remains a number and will be useable in calculations further. The Text will possible lead to issues while used in calculations.
If you cannot set own data-tableexport-msonumberformat attributes to TD elements, then you could extend the tableExport.jquery.plugin.
In tableExport.js have:
...
var defaults = {
onMsoNumberFormat: onMsoNumberFormat,
...
onMsoNumberFormat must be a function.
If the function onMsoNumberFormat is like:
onMsoNumberFormat = function(cell, row, col) {
if (row > 0 && col == 2) {
return "#\\,##0\\.00";
}
if (row > 0 && col == 3) {
return "\\#";
}
};
then the third column (col==2) from row 2 (row>0) upwards will get style="mso-number-format:#\,##0\.00" and the fourth column (col==3) from row 2 (row>0) upwards will get style="mso-number-format:\#". # is Textformat.
Example:
http://jsfiddle.net/uqtubq5c/3/

How to extracting Data from HTML table using php

I keep trying different methods of extracting the data from the HTML table such as using xpath. The table(s) do not contain any classes so I am not sure how to use xpath without classes or Id. This data is being retrieved from an rss xml file. I am currently using DOM. After I extract the data, I will try to sort, the tables by Job Title
Here is my php code
$html='';
$xml= simplexml_load_file($url) or die("ERROR: Cannot connect to url\n check if report still exist in the Gradleaders system");
/*What we do here in this loop is retrieve all content inside the encoded content,
*which includes the CDATA information. This is where the HTML and styling is included.
*/
foreach($xml->channel->item as $cont){
$html=''.$cont->children('content',true)->encoded.'<br>'; //actual tag name is encoded
}
$htmlParser= new DOMDocument(); //to parse html using DOMDocument
libxml_use_internal_errors(true); // your HTML gives parser warnings, keep them internal
$htmlParser->loadHTML($html); //Loaded the html string we took from simple xml
$htmlParser->preserveWhiteSpace = false;
$tables= $htmlParser->getElementsByTagName('table');
$rows= $tables->item(0)->getElementsByTagName('tr');
foreach($rows as $row){
$cols = $row->getElementsByTagName('td');
echo $cols;
}
This is the HTML I am extracting info from
<table cellpadding='1' cellspacing='2'>
<tr>
<td><b>Job Title:</b></td>
<td>Job Example </td>
</tr>
<tr>
<td><b>Job ID:</b></td>
<td>23992</td>
</tr>
<tr>
<td><b>Job Description:</b></td>
<td>Just a job example </td>
</tr>
<tr>
<td><b>Job Category:</b></td>
<td>Work-study Position</td>
</tr>
<tr>
<td><b>Position Type:</b></td>
<td>Work-study</td>
</tr>
<tr>
<td><b>Applicant Type:</b></td>
<td>Work-study</td>
</tr>
<tr>
<td><b>Status:</b></td>
<td>Active</td>
</tr>
<tr>
<td colspan='2'><b><a href='https://www.myjobs.com/tuemp/job_view.aspx?token=I1iBwstbTs2pau+SjrYfWA%3d%3d'>Click to View More</a></b></td>
</tr>
</table>
You can use xpath to query('//td') and retrieve the td html using C14N(), something like:
$dom = new DOMDocument();
$dom->loadHtml($html);
$x = new DOMXpath($dom);
foreach($x->query('//td') as $td){
echo $td->C14N();
//if just need the text use:
//echo $td->textContent;
}
Output:
<td><b>Job Title:</b></td>
<td>Job Example </td>
<td><b>Job ID:</b></td>
...
C14N();
Returns canonicalized nodes as a string or FALSE on failure
Update:
Another question, how can I grab individual Table Data? For example,
just grab, Job ID
Use XPath contains, i.e.:
foreach($x->query('//td[contains(., "Job ID:")]') as $td){
echo $td->textContent;
}
Update V2:
How can I get the next Table Data after that (to actually get the Job
Id) ?
Use following-sibling::*[1], i.e:
echo $x->query('//td[contains(*, "Job ID:")]/following-sibling::*[1]')->item(0)->textContent;
//23992
$xpathParser = new DOMXPath($htmlParser);
$tableDataNodes = $xpathParser->evaluate("//table/tr/td")
for ($x=0;$x<$tableDataNodes.length;$x++) {
echo $tableDataNodes[$x];
}

Removing the last column of an HTML table - using preg_replace

in a simple HTML table I would like to remove the last column
<table>
<tbody>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th rowspan="3">I want to remove this</th>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td rowspan="3">I want to remove this</td>
</tr>
I am using this code, but I am still left with the content and the th and td rowspan
$myTable = preg_replace('#</?td rowspan[^>]*>#i', '', $myTable);
echo $myTable
Question: how do I remove the last column and it's content ?
<?php
// Create a new DOMDocument and load the HTML
$dom = new DOMDocument('1.0');
$dom->loadHTML($html);
// Create a new XPath query
$xpath = new DOMXPath($dom);
// Find all elements with a rowspan attribute
$result = $xpath->query('//*[#rowspan]');
// Loop the results and remove them from the DOM
foreach ($result as $cell) {
$cell->parentNode->removeChild($cell);
}
// Save back to a string
$newhtml = $dom->saveHTML();
See it working
I guess this will do it
preg_replace("/<(?:td|th)[^>]*>.*?<\/(?:td|th)>\s+<\/tr>/i", "</tr>", $myTable);
assuming you have closing tr tag (</tr>) at the end of each row unlike in your example
Edit: this will remove any <td> or <th> elements before closing </tr> no matter if they have any attributes
working example

Categories