As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I have a php file which queries a database and then writes and updates the html accordingly.
I have a button on this page "Export As PDF"..I am trying to convert this page to a pdf using HTML2FPDF, but I get the following error:
FPDF error: Unable to create output file: Entry Report
I suspect the problem is because I am passing a php file instead of a html file:
<?php
require('html2fpdf.php');
if(isset($_POST['link'])){
$url = $_POST['link'];
$nm = $_POST['nm'];
convert($url, $nm);
}
function convert($link, $name){
$pdf=new HTML2FPDF();
$pdf->AddPage();
$fp = fopen($link,"r");
$strContent = fread($fp, filesize($link));
fclose($fp);
$pdf->WriteHTML($strContent);
$pdf->Output($name);
echo ("PDF file generated successfully!");
}
?>
Does anyone know how I can get around this? perhaps by either converting php to html then html to pdf...
Or is there a direct way to convert a php file into a pdf file...
EDIT: OK so the problem was that I didn't allow public write permissions. Upon changing this, I managed it to create the pdf file...The problem is this....the pdf file is blank...
I know this has something to do with the fact that I am passing a php page which is probably empty when it is being passed...How do I capture the html content within the html so the pdf output isn't blank?
Here is the php page:
<?php
function connect() {
$dbh = mysql_connect ("localhost", "user", "password") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db("PDS", $dbh);
return $dbh;
}
session_start();
if(isset($_SESSION['username'])){
if(isset($_POST['entryId'])){
//do something
$dbh = connect();
$ide = $_POST['entryId'];
$usertab = $_POST['usertable'];
$answertable = $usertab . "Answers";
$entrytable = $usertab . "Entries";
$query = mysql_query("SELECT e.date, q.questionNumber, q.question, q.sectionId, a.answer FROM $answertable a, Questions q, $entrytable e WHERE a.entryId = '$ide' AND a.questionId = q.questionId AND e.entryId = '$ide' ORDER BY q.questionNumber ASC;") or die("Error: " . mysql_error());
if($query){
//set variables
$sectionOne = array();
$sectionTwo = array();
$sectionThree = array();
$sectionFour = array();
$sectionFive = array();
while($row=mysql_fetch_assoc($query)){
$date = $row['date'];
$section = $row['sectionId'];
switch($section){
case '1':
$sectionOne[] = $row;
break;
case '2':
$sectionTwo[] = $row;
break;
case '3':
$sectionThree[] = $row;
break;
case '4':
$sectionFour[] = $row;
break;
case '5':
$sectionFive[] = $row;
break;
default:
break;
}
}
}else{
//error - sql failed
}
}
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src = "jQuery.js"></script>
<script>
$(document).ready(function(){
$("#export").click(function(e){
//post to html2pdfconverter.php
$("#link").val("Testers/viewentryreport.php");
$("#nm").val("Entry Report.pdf");
$("form#sendanswers").submit();
});
});
</script>
<title>Personal Diary System - Entry Report - <?php echo($date); ?></title>
</head>
<body>
<h1>Entry Report - <?php echo($date); ?></h1>
<div id = "buttons">
<form id = "sendanswers" name = "sendanswers" action="Testers/html2pdfconverter.php" method="post">
<input type = "hidden" name = "link" id = "link" value = "">
<input type = "hidden" name = "nm" id = "nm" value = "">
<input type = "button" name = "export" id = "export" value = "Export As PDF"/>
</form>
</div>
<h3>Biological Information</h3>
<?php
$i = 0;
foreach($sectionOne as &$value){
if($i == 1 || $i == 3){
$image = "assets/urine".$i.".png";
echo("<br/>");
echo($value['question']." <br/> "."<img src = \"$image\"/>");
echo("<br/>");
}else{
echo($value['question'].' : '.$value['answer']);
}
echo("<br/>");
$i++;
}
?>
<h3>Fatigue and Recovery</h3>
<?php
foreach($sectionTwo as &$value){
echo($value['question'].' : '.$value['answer']);
echo("<br/>");
}
?>
<h3>Illness and Injury</h3>
<?php
foreach($sectionThree as &$value){
echo($value['question'].' : '.$value['answer']);
echo("<br/>");
}
?>
<h3>Training Sessions</h3>
<?php
foreach($sectionFour as &$value){
echo($value['question'].' : '.$value['answer']);
echo("<br/>");
}
?>
<h3>General Feedback</h3>
<?php
if(count($sectionFive)>0){
foreach($sectionFive as &$value){
echo($value['question'].' : '.$value['answer']);
}
}else{
$sectionFive = "User didn't leave any feedback";
echo("User didn't leave any feedback");
}
echo("<br/>");
?>
</body>
</html>
<?php
}
?>
and html2pdfconverter.php
<?php
require('html2fpdf.php');
if(isset($_POST['link'])){
$url = $_POST['link'];
$nm = $_POST['nm'];
convert($url, $nm);
}
function convert($link, $name){
$pdf=new HTML2FPDF();
$pdf->AddPage();
$fp = fopen($link,"r");
$strContent = fread($fp, filesize($link));
fclose($fp);
$pdf->WriteHTML($strContent);
$pdf->Output($name);
echo ("PDF file generated successfully!");
}
?>
EDIT #TIMFERRIS
I changed my convert function to this based on #TimeFerris' answer:
function convert($link, $name){
$pdf=new HTML2FPDF();
$pdf->AddPage();
$content = file_get_contents( $link ); //shorter than what you did
ob_start();
echo $content;
$pdf->WriteHTML( ob_get_contents() );
ob_end_clean();
$pdf->Output($name);
echo ("PDF file generated successfully!");
}
The PDF file is created but still blank
I recently done this by using TCPDF. TCPDF is a further developed version of FPDF.
See this link for an expample regarding converting to PDF. Also, here you can find more examples. Example 61 could also come in quite handy.
Sample code which TCPDF uses:
$html = '<h1>HTML Example</h1>
<div style="text-align:center">IMAGES<br />
<img src="../images/logo_example.png" alt="test alt attribute" width="100" height="100" border="0" /><img src="../images/tiger.ai" alt="test alt attribute" width="100" height="100" border="0" /><img src="../images/logo_example.jpg" alt="test alt attribute" width="100" height="100" border="0" />
</div>';
// output the HTML content
$pdf->writeHTML($html, true, false, true, false, '');
One thing that you could do is run the PHP file, but use output buffering to capture the contents that the PHP script is writing out. Then, save those contents to an .html file and pass that file to the converter.
The php file you are supplying has to run through a parser before it's valid html code.
$content = file_get_contents( $filename ); //shorter than what you did
ob_start();
echo $content;
$pdf->WriteHTML( ob_get_contents() );
ob_end_clean();
Related
I have forms.
On the forms should be adding files to the Files folder. (It works, but there is a problem) when I only add a file, it is not added, this error appears instead:
Warning:Cannot modify header information -headers already sent by (output started at Q:\home\rat\www\pr5\files.php:1) in Q:\home\rat\www\pr5\files.php on line 10
The file of the file in the Files folder (it does not work: constantly writes that the file exists, even if there is no such file)
The image of the added files (it works too)
Deleting files (it does not work completely, the files are not deleted), this error appears:
Warning: unlink(files/Удалить) [function.unlink]: No such file or directory in Q:\home\rat\www\pr5\files.php on line 61
What is the problem with the paths of me? I can not understand. I did everything on the textbook, but does not work ...
files.php
<?
class Files {
public $files;
function __construct() {
$this->files = scandir("files/");
}
function redirect($url) {
header('Location: '.$url);
}
function counter() {
$filename = "count.txt";
if(file_exists($filename)) {
$h = fopen($filename, "r+");
$Content = fread($h, filesize($filename));
fclose($h);
$text = $Content + 1;
} else {
$text = 1;
}
$h = fopen($filename, "w");
if(fwrite($h, $text)) {
echo "Вы $text-й посетитель сайта =)";
} else {
echo "Что-то не работает на сайте! =(";
echo "Надо напрячь прогера!";
}
fclose($h);
echo "<hr>";
}
function upload() {
if($_FILES['myfile']) {
$uploaddir = 'files/';
$destination = $uploaddir.$_FILES['myfile']['name'];
if(move_uploaded_file($_FILES['myfile']['tmp_name'], $destination)) {
$this->redirect('/pr5');
} else {
return "error <br>";
}
}
}
function search() {
if($_POST['searchname']) {
$folder = "files/";
$file = $searchname;
$file = $folder.$file;
if(file_exists($file)) {
print "Файл существует";
} else {
print "Файл не существует";
}
}
}
function delete() {
if($_POST['delete']) {
unlink("files/".$_POST['delete']);
$this->redirect('/pr5');
}
}
}
?>
index.php
<?
include "files.php";
$f = new Files;
if($_FILES['myfile']) {
$f->upload();
}
if($_POST['delete']) {
$f->delete();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>pr5</title>
</head>
<body>
<?
$f->counter();
?>
<form enctype = "multipart/form-data" method = "post">
<input type = "hidden" name = "MAX_FILE_SIZE" value = "30000" />
<input type = "file" name = "myfile" /><br>
<input type = "submit" value = "Отправить" />
</form>
<hr>
<form enctype = "multipart/form-data" method = "post">
<input type = "text" name = "searchname" /><br>
<input type = "submit" value = "Найти" />
</form>
<?
if($_POST['searchname']) {
$f->search();
}
?>
<hr>
<?
if(count($f->files) > 2) {
?>
<form method = "POST">
<table>
<tr>
<th>Имя</th>
<th>Удалить</th>
</tr>
<?
foreach($f->files as $s) {
?>
<?
if($s != '.' and $s != '..') {
?>
<tr>
<td> <?
echo $s;
?> </td>
<td>
<button type = "submit" name = "delete" value = "<? echo $s; ?>">Удалить</button>
</td>
</tr>
<?
}
?>
<?
}
?>
</table>
</form>
<?
}
?>
</body>
</html>
Okay, let's check this error more closely.
Warning: Cannot modify header information -headers already sent
PHP cannot modify headers - so the point where it realizes something's amiss is when it calls the header() function - because
output started at Q:\home\rat\www\pr5\files.php:1)
So, in that file, at row 1, there is something output. Something that's not PHP.
What appears to be line 1 is just
<?
which should have been perfectly copacetic (well, actually you'd better take the habit of using long tags, so, "<?php", since that's the established standard).
I am therefore betting something that in that line, unless there is an empty line before it of course, there is something you cannot see. My money is on a BOM: three invisible bytes that tell the operating system that file is coded in UTF8 with specific characteristics.
Usually, your editor should have an option to create files without a Byte Order Mark.
im new in php programming and ive a problem recently. I have 1 html page with a Search Box and a php script using for grep in a specific file on local host. This is what i want, when a user type string of char and click on enter that send a POST to modify my php var $contents_list, and grep all filename where the string is found.
<?php
$contents_list = $_POST['search'];
$path = "/my/directory/used/for/grep";
$dir = new RecursiveDirectoryIterator($path);
$compteur = 0;
foreach(new RecursiveIteratorIterator($dir) as $filename => $file) {
$fd = fopen($file,'r');
if($fd) {
while(!feof($fd)) {
$line = fgets($fd);
foreach($contents_list as $content) {
if(strpos($line, $content) != false) {
$compteur+=1;
echo "\n".$compteur. " : " . $filename. " : \n"."\n=========================================================================\n";
}
}
}
}
fclose($fd);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<form action="page2.php" method="post">
<INPUT TYPE = "TEXT" VALUE ="search" name="search">
</form>
</body>
And when i go to my html page and type text in searchbar, that redirect me to my php script "localhost/test.php" and i have 500 internal error.
So I want:
To see result of the php script on the same html page, but i dont know how to do that :/
And if the previous filename return was same like previous result, dont print it, to avoid double result.
I hope its clear and youve understand what i want to do, so thanks for the people who want to help me <3
My recommendations:
Combine the code into the single index.php file for simplicity
Separate logic for search and output to achieve clean separation of duties
Add helper text such as nothing found or enter text
index.php content:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<form action="index.php" method="post">
<input type="text" placeholder="search" name="search">
</form>
<?php
// Check if the form was submitted.
if (isset($_POST['search']) && (strlen($_POST['search'])) > 0) {
$search_line = $_POST['search'];
$path = "/my/directory/used/for/grep";
$dir_content = new RecursiveDirectoryIterator($path);
// Array to store results.
$results = [];
// Iterate through directories and files.
foreach (new RecursiveIteratorIterator($dir_content) as $filename => $file) {
$fd = fopen($file, 'r');
if ($fd) {
while (!feof($fd)) {
$file_line = fgets($fd);
if (strpos($file_line, $search_line) !== FALSE) {
$results[] = $filename;
}
}
fclose($fd);
}
}
// Output result.
echo "<pre>";
if ($results) {
foreach ($results as $index => $result) {
echo ($index + 1) . " :: $result\n";
}
}
else {
echo "Nothing found!";
}
echo "</pre>";
}
else {
// When nothing to search.
echo "<pre>Enter something to search.</pre>";
}
?>
</body>
</html>
This is a critical scenario.I have 2 pages such as
output.php has dynamic table data with style which is get from excel.
<?php
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/');
include 'PHPExcel/IOFactory.php';
/* EXCEL TABLE */
$inputFileName2 = 'C:\inetpub\wwwroot\Monthly-EDM\Action_items.xlsx';
try {
$objPHPExcel1 = PHPExcel_IOFactory::load($inputFileName2);
}
catch (Exception $e) {
die('Error loading file "' . pathinfo($inputFileName2, PATHINFO_BASENAME) . '": ' . $e->getMessage());
}
/* Open an Excel & count */
$allDataInSheet = $objPHPExcel1->getActiveSheet()->toArray(null, true, true, true);
$arrayCount = count($allDataInSheet); // Here get total count of row in that Excel sheet
$file = fopen($inputFileName2, "r");
fclose($file);
echo '<table width="800" border="0" cellspacing="0" cellpadding="0" align="center">';
echo '<tr>';
echo '</td>';
/* <th> code here */
echo '</td>';
echo ' </tr>';
echo ' <!-- Header blue row - end -->';
echo '<style>.shiva:nth-child(odd) { background-color:#b9b8bb; }</style>';
echo '<style>.shiva:nth-child(even) { background-color:#e5e8e8; }</style>';
for ($i = 2; $i <= $arrayCount; $i++) {
$_SESSION["a"] = trim($allDataInSheet[$i]["A"]);
$_SESSION["b"] = trim($allDataInSheet[$i]["B"]);
$_SESSION["c"] = trim($allDataInSheet[$i]["C"]);
$_SESSION["d"] = trim($allDataInSheet[$i]["D"]);
$_SESSION["e"] = trim($allDataInSheet[$i]["E"]);
$_SESSION["f"] = trim($allDataInSheet[$i]["F"]);
$_SESSION["g"] = trim($allDataInSheet[$i]["G"]);
echo ' <tr>';
echo '<td>';
echo '</td>';
echo ' </tr>';
}
echo '<!-- table content - end --> ';
echo '</table>';
echo '</td>';
echo ' </tr>';
echo '</table>';
?>
get.html (I want to get the output of output.php here)
Click to view the result of the output.php
How to get the output of output.php and pass this output to get.html page and show the output.Is this possible to access the php output from html page??
Thanks in advance.Please help me to fix it.
Here is one solution (this solution assumes you are using Apache)
Create a .htaccess file at the root of your site. Put this in the .htaccess file:
AddType application/x-httpd-php .html .htm
This file will make Apache parse .html files as PHP. Then in your get.html file, put this code:
<html>
<head></head>
<body><?php include('path/to/output.php'); ?></body>
</html>
If you view the get.html file in your browser, you will see the output of output.php
Here is an alternative solution using Javascript and AJAX:
Put the following code in your get.html file. This will make an ajax request to your output.php file and put the response in a <div id="output"></div>.
<html>
<head></head>
<body>
<div id="output"></div>
<script>
var request = new XMLHttpRequest();
request.open('GET', 'output.php', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
document.getElementById('output').innerHTML = request.responseText;
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
</script>
</body>
</html>
I'm not 100% sure, if this is what you mean. But if you make a file (foo.php) and put it in the same directory as where output.php is, and then add this to foo.php:
<?php
$myfile = fopen("output.php", "r") or die("Unable to open file!");
echo fread($myfile,filesize("output.php"));
fclose($myfile);
?>
Then that should print the content of output.php in your browser, as HTML (if you go to /foo.php in the browser).
Is that it?
I have the following code that opens a non-txt file and runs through it so it can read the file line by line, i want to create a textbox (using html probably) so i can put my readed text into that but i have no idea how to do it
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<h2>testing</h2>
<?php
$currentFile = "pathtest.RET";
$fp = fopen($currentFile , 'r');
if (!$fp)
{
echo '<p> FILE NOT FOUND </p>';
exit;
}
else
{
echo '<p><strong> Arquivo:</strong> ['. $currentFile. '] </p>';
}
$numLinha = 0;
while (!feof($fp))
{
$linha = fgets($fp,300);
$numLinha = $numLinha + 1;
echo $linha;
}
fclose($fp);
$numLinha = $numLinha -1;
echo '<hr>linhas processadas: ' . $numLinha;
?>
</body>
</html>
i need the textbox area to be in a form so i can define the cols and rows, or there is an way to do it in php ? is there any way to send the readed content to another .php so i can edit the php to an html interface style freely ?
Try echoing the lines between a textarea:
echo "<textarea>";
while (!feof($fp))
{
$linha = fgets($fp,300);
$numLinha = $numLinha + 1;
echo $linha;
};
echo "</textarea>";
You may use \n in order to break lines on the textarea:
echo $linha . "\n";
I am trying to capture the contents of my php page using output buffering:
<?php
function connect() {
$dbh = mysql_connect ("localhost", "user", "password") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db("PDS", $dbh);
return $dbh;
}
session_start();
if(isset($_SESSION['username'])){
if(isset($_POST['entryId'])){
//do something
$dbh = connect();
$ide = $_POST['entryId'];
$usertab = $_POST['usertable'];
$answertable = $usertab . "Answers";
$entrytable = $usertab . "Entries";
$query = mysql_query("SELECT e.date, q.questionNumber, q.question, q.sectionId, a.answer FROM $answertable a, Questions q, $entrytable e WHERE a.entryId = '$ide' AND a.questionId = q.questionId AND e.entryId = '$ide' ORDER BY q.questionNumber ASC;") or die("Error: " . mysql_error());
if($query){
//set variables
$sectionOne = array();
while($row=mysql_fetch_assoc($query)){
$date = $row['date'];
$sectionOne[] = $row;
}
}else{
//error - sql failed
}
}
?>
<?php
ob_start();
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src = "jQuery.js"></script>
<script>
$(document).ready(function(){
$("#export").click(function(e){
//post to html2pdfconverter.php
$("#link").val("<?php echo(ob_get_contents()); ?>"); //THIS DOESN'T WORK
$("#nm").val("Entry Report.pdf");
$("form#sendanswers").submit();
});
});
</script>
<title>Personal Diary System - Entry Report - <?php echo($date); ?></title>
</head>
<body>
<h1>Entry Report - <?php echo($date); ?></h1>
<div id = "buttons">
<form id = "sendanswers" name = "sendanswers" action="html2pdfconverter.php" method="post">
<input type = "hidden" name = "link" id = "link" value = "">
<input type = "hidden" name = "nm" id = "nm" value = "">
<input type = "button" name = "export" id = "export" value = "Export As PDF"/>
</form>
</div>
<h3>Biological Information</h3>
<?php
echo('<p>');
$i = 0;
foreach($sectionOne as &$value){
if($i == 1 || $i == 3){
$image = "assets/urine".$i.".png";
echo("<br/>");
echo($value['question']." <br/> "."<img src = \"$image\"/>");
echo("<br/>");
}else{
echo($value['question'].' : '.$value['answer']);
}
echo("<br/>");
$i++;
}
echo('</p>');
?>
</body>
</html>
<?php
}
$contents = ob_get_contents(); //THIS WORKS
ob_end();
?>
I assign the contents of ob to $contents using ob_get_contents(); This works, and echoing $contents duplicates the html page.
However, in my jQuery, I am trying to assign this to a hidden text field ('link') using:
$("#link").val("<?php echo($contents); ?>");
This doesn't work however..And I have a feeling its because I am accessing $contents too eraly but not too sure...any ideas?
$("#link").val("<?php echo(ob_get_contents()); ?>"); //THIS DOESN'T WORK
at the point you do that ob_get_contents call, you've only output about 10 lines of javascript and html. PHP will NOT reach back in time and magically fill in the rest of the document where you do this ob_get_contents().
You're basically ripping the page out of the laser printer the moment the page starts emerging, while the printer is still printing the bottom half of the page.
I fail to see why you want to embed the contents of your page into an input field. If you want to somehow cache the page's content in an input field, you can just use JS to grab the .innerHTML of $('body').
Well, you have two problems.
The first is what you suspect. You can't access that stuff until later. The second problem which you may not realize is that you will have quoting issues in JavaScript even if you manage to find a way to reorder this and make it work. It's recursive, in a bad way.
What you should do instead is change your $('#export').click handler to do an Ajax call, render the HTML you need to appear in the link on the server in a separate PHP script (no output buffering necessary) and then have your code inject the result of that call into the page the way you're trying to do in your click handler now.