PHP Loop Concantination Save File

I have a web page that has a Save As PDF button on it.  There is a function that compiles data via a foreach loop and populates a variable with specific information:  This variable, when finished is a document that can be saved as a PDF.  I am using file called dompdf.php


<?php		
	$query = $this->db->select('*')
	->from('TABLE')
	->where('id', $d)
	->get();	
items = $query->result_array();
$query->free_result();
	foreach ($items as $row)
		{
$htmldoc.= '<html>
	<head>
	<title></title>
<style type="text/css">
	body {
	font-family: Times New Roman;
	font-size: 15px;
	}
      .my-contract{
	width:750px;
	margin:0px auto;
	}
</style>
	</head>
	<body style="margin: 1px">
               <div class="my-contract">'.$variables.'</div>
	</body>
</html>';
}  //  END OF FOREACH LOOP

$dompdf = new DOMPDF();
		$dompdf->load_html($htmldoc);
		$dompdf->render();
?>

Open in new window

This query loops any where from 1 -10 times depending on other factors.  I get an error : undefined variable $htmldoc  Where do I start looking to figure this out?
LVL 7
rgranlundAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ray PaseurCommented:
I would start by adding error_reporting(E_ALL) to the top of the script.  There may be errors you cannot see.

If there is an "undefined variable" message, you might find a line number in that message.  That is where the error occurred.  So look "logically upstream" to find the code that might have caused the variable to be undefined.  This is usually some kind of conditional statement, such as an if() or while() statement.
0
Dave BaldwinFixer of ProblemsCommented:
PHP will give you that error when you first use a variable by adding to it like...
$htmldoc.=

Open in new window

because the '.=' implies that something already exists.

You need to do at least a basic assignment before the 'foreach' loop like this.
$htmldoc = '';

Open in new window

Now the variable exists and you can add/concatenate other strings to it.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
rgranlundAuthor Commented:
I followed all of the instructions but now a new issue has arisen.
The following only saves the last iteration on the htmldoc loop.
<?php		
	$query = $this->db->select('*')
	->from('TABLE')
	->where('id', $d)
	->get();	
items = $query->result_array();
$query->free_result();
	foreach ($items as $row)
		{
$htmldoc = '<html>
	<head>
	<title></title>
<style type="text/css">
	body {
	font-family: Times New Roman;
	font-size: 15px;
	}
      .my-contract{
	width:750px;
	margin:0px auto;
	}
</style>
	</head>
	<body style="margin: 1px">';

$htmldoc.= ' <div class="my-contract">'.$variables.'</div>';
 $htmldoc.= '</body></html>';
}  //  END OF FOREACH LOOP

$dompdf = new DOMPDF();
		$dompdf->load_html($htmldoc);
		$dompdf->render();
?>

Open in new window


The following clears the page and nothing happens.
<?php		
	$query = $this->db->select('*')
	->from('TABLE')
	->where('id', $d)
	->get();	
items = $query->result_array();
$query->free_result();
	foreach ($items as $row)
		{
$htmldoc = '<html>
	<head>
	<title></title>
<style type="text/css">
	body {
	font-family: Times New Roman;
	font-size: 15px;
	}
      .my-contract{
	width:750px;
	margin:0px auto;
	}
</style>
	</head>
	<body style="margin: 1px">';

$htmldoc.= ' <div class="my-contract">'.$variables.'</div>';
 $htmldoc.= '</body></html>';
}  //  END OF FOREACH LOOP

return $this->$htmldoc;

$dompdf = new DOMPDF();
		$dompdf->load_html($htmldoc);
		$dompdf->render();
?>

Open in new window

0
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

Ray PaseurCommented:
Well, the logic in the first script will cause the foreach loop to create a new HTML document every time, inside the $htmldoc variable.  I'm fairly sure that's not what you want, but I don't really know what you want.  If you're trying to produce a PDF document, the fastest and easiest path I've found is to use FPDF or TCPDF.  They are both free and open source, object oriented (so you can extend the classes) and very easy to use.  Perhaps if you can show us what your data looks like and show us what you want to get for output we can help more.  But even without that I can show you how to use both of these classes at the "hello world" level.

FPDF
<?php // demo/fpdf_hello_world.php
error_reporting(E_ALL);


// DEMONSTRATE SOME OF THE BASICS OF FPDF


// SOME VARIABLES FOR OUR TESTS (COULD COME FROM DATA BASE, ETC)
$font = 'Arial';
$text = 'Hello World!';

// BRING IN THE PDF THING
require_once('fpdf16/fpdf.php');

// SYNTHESIZE THE PDF FILE INFORMATION
$pdf_file_link
= 'storage'
. DIRECTORY_SEPARATOR
. 'temp_pdf_blue'
. '.pdf'
;
$pdf_file_name
= getcwd()
. DIRECTORY_SEPARATOR
. $pdf_file_link
;

// DO THE HELLO WORLD EXERCISE IN WHITE ON A BLUE BACKGROUND
$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont($font, 'B', 16);
$pdf->SetFillColor(  0,   0, 255);
$pdf->SetTextColor(255, 255, 255);
$pdf->Cell(40, 10, $text, 0, 2, 'L', TRUE);

// WRITE THE PDF TO DISK
$pdf->Output($pdf_file_name, 'F');

// PRESENT A LINK
echo '<a target="my_PDF" href="' . $pdf_file_link . '">Blue PDF</a>';



// START OVER FOR A NEW PDF
unset($pdf);
echo PHP_EOL . "<br/>";

// SYNTHESIZE THE PDF FILE INFORMATION
$pdf_file_link
= 'storage'
. DIRECTORY_SEPARATOR
. 'temp_pdf_red'
. '.pdf'
;
$pdf_file_name
= getcwd()
. DIRECTORY_SEPARATOR
. $pdf_file_link
;

// DO THE HELLO WORLD EXERCISE IN BLACK ON A RED BACKGROUND
$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont($font, 'B', 24);
$pdf->SetFillColor(255,   0,   0);
$pdf->SetTextColor(  2,   2,   2);
$pdf->Cell(52, 10, $text, 0, 2, 'L', TRUE);

// WRITE THE PDF TO DISK
$pdf->Output($pdf_file_name, 'F');

// PRESENT A LINK
echo '<a target="my_PDF" href="' . $pdf_file_link . '">Red PDF</a>';

Open in new window


TCPDF
<?php // demo/tcpdf_example.php

/**
 * Demonstrate how to put an image into a TCPDF document
 * and write some text over part of the image
 *
 * See http://www.tcpdf.org/doc/code/annotated.html
 */
error_reporting(E_ALL);

// A DATE SETTING MAY BE REQUIRED - DEPENDS ON PHP INSTALLATION SETTINGS
date_default_timezone_set('America/Chicago');

// SYNTHESIZE THE PDF FILE URL AND FILE NAME
$pdf_file_link    = 'storage/tcpdf_example.pdf';
$pdf_file_name    = getcwd() . DIRECTORY_SEPARATOR . $pdf_file_link;

// LOAD THE TCPDF CLASS AND CONFIGURATION
require_once('tcpdf/config/lang/eng.php');
require_once('tcpdf/tcpdf.php');

// EXTEND THE TCPDF OBJECT SO WE CAN SUBSTITUTE OUR OWN METHODS
class PDF extends TCPDF
{
    // NULLIFY AUTOMATIC HEADER AND FOOTER
    public function Header() {}
    public function Footer() {}
}

// INSTANTIATE THE OBJECT
$pdf = new PDF('P', 'mm', 'LETTER', true, 'UTF-8', false);
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
$pdf->SetMargins(0,0,0,TRUE);
$pdf->SetAutoPageBreak(FALSE);
$pdf->setLanguageArray($l);
$pdf->SetFont('times', '', 13);
$pdf->setCellPaddings(0,0,0,0);
$pdf->setCellMargins(0,0,0,0);

// DO NOT DO THIS
// $pdf->setFillColor(255,255,224);


// APPLY CELL BORDERS, IF NEEDED
$bdr = '1TRBL';

// BUT IF NO CELL BORDER IS NEEDED
$bdr = 0;

// ADD A PAGE
$pdf->AddPage('P', 'LETTER', TRUE);

// ADD AN IMAGE
$img = 'images/ray_padded.png';

// I HAVE NO IDEA WHAT THIS IS DOING TO IMAGE SCALE - EXPERIMENT WITH IT
$pdf->setImageScale(1.53);

// GET THE IMAGE SETTINGS
$pdf->Image
( $img
, 0             // $x
, 0             // $y
, 0             // WIDTH
, 0             // HEIGHT
, 'PNG'         // TYPE
, '#'           // LINK URL
, 'T'           // SET POINTER TOP LEFT
, FALSE         // NO RESIZING
, 300           // DPI
, 'L'           // PALIGN
, FALSE         // ISMASK
, FALSE         // IMGMASK
, 0             // BORDER
, FALSE         // FIT TO BOX
, FALSE         // HIDDEN
, FALSE         // FIT ON PAGE
)
;

// ADD SOME TEXT ON TOP OF THE IMAGE
$pdf->Text
( 24            // $x,
, 24            // $y,
, 'This is Ray'
, FALSE         // $fstroke           = false,
, FALSE         // $fclip             = false,
, TRUE          // $ffill             = true,
, $bdr          // $border            = whatever,
, 2             // $ln                = 0, 2=PUT CURSOR BELOW
, ''            // $align             = '', DEFAULT LEFT
, FALSE         // $fill              = false, CELL BACKGROUND
, ''            // $link              = '', NOT A LINK
, 0             // $stretch           = 0, NO TEXT STRETCH
, FALSE         // $ignore_min_height = false,
, 'A'           // $calign            = 'T', A=FONT TOP INSIDE CELL
, 'T'           // $valign            = 'M', T=VERTICAL ALIGN INSIDE CELL
, TRUE          // $rtloff            = false TRUE = USE PAGE TOP LEFT CORNER TO ALIGN
)
;

// WRITE THE PDF FILE TO THE SERVER
$pdf->Output($pdf_file_name, 'F');

// PRESENT A CLICKABLE LINK SO WE CAN D/L AND PRINT THE PDF
echo '<a target="my_PDF" href="' . $pdf_file_link . '"><strong>Print the PDF</strong></a>';

Open in new window

0
rgranlundAuthor Commented:
The $dompdf code that I am using works great.  What I am trying to do is have one html document that has a div inside that repeats with each iteration of the foreach loop.

Maybe it is something like this?

<?php
$html_open = '<html><head></head><body style="margin: 1px">';
$htmldoc = "";
 $html_close = '</body></html>';

$query = $this->db->select('*')
	->from('TABLE')
	->where('id', $d)
	->get();	
items = $query->result_array();
$query->free_result();
	foreach ($items as $row)
		{
$htmldoc.= ' <div class="my-contract">'.$variables.'</div>';
}

$dompdf = new DOMPDF();
		$dompdf->load_html($html_open, $htmldoc, $html_close);
		$dompdf->render();

Open in new window

0
Dave BaldwinFixer of ProblemsCommented:
That last code is what I was talking about.  $htmldoc = ""; is before the foreach loop so the $htmldoc.= '... code will work properly.
0
Ray PaseurCommented:
That strategy looks better, but it looks like $variables is undefined in this script.
0
Slick812Commented:
greetings rgranlund,  you do not have any sort of code here to do any "writing" of a web HTML page. You do not have a proper foreach loop, to write multiple <div> inside a Properly done HTML page. First and foremost in your shortcomings is your complete lack of using the very, very Important   $row   variable from your Database Query.
$htmldoc = '<!DOCTYPE HTML><html>
	<head><title>My Page</title>
<style>
	body {
	font-family: Times New Roman;
	font-size: 15px;
        margin: 1px
	}
      .my-contract{
	width:750px;
	margin:0px auto;
	}
</style>
	</head>
	<body>';

               
foreach ($items as $row)
		{
$htmldoc .= ' <div class="my-contract">First is '.$row[0].', Next is '.$row[1]."</div>\n";
}

$htmldoc .= '</body></html>';

echo $htmldoc;

Open in new window

The above code has a better arrangement to get a web page output to the Return from this PHP page.
HOWEVER, I have NO idea what is in your Database  $row  result, so I just used this  -  $row[0]   - for an example, , BUT there is no decent page output from any code such as -
     <div class="my-contract">'.$variables.'</div>

as YOU  need to set up your page TEXT output here, by Naming the $row elements in the Text output.
0
rgranlundAuthor Commented:
I am aware that I did not define $variables in my example, I assumed that the experts would would "Just know" that they were going to be defined.  I will continue to formulate my questions better, more thoroughly so as to avoid an confusion and get to the core issue much quicker.  Thanks for your helpful input and suggestions.
0
Dave BaldwinFixer of ProblemsCommented:
Glad we were able to help.  One of the most common problems in coding is the things that are missing in the code.  It does make it easier to help you when your examples are more complete.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.