i need to put some html content in a variable for generating pdf using mpdf, is there any way to assign html content to a variable in a php function.
this is what i am trying.
function getInvoice($conn,$uid,$id,$invoice_no)
{
echo "something";
ob_start();
?>
$content='<html>
<body style="padding-top: 0px">
<page>
my html content
</page><body><?php echo "something"?;></body><html>'
<?php
$content .= ob_get_clean();
}
?>
What i need is that the all the content in html get assign to $content variable.
It is not working because it is between php execution function.
Try like this.
function getInvoice($conn,$uid,$id,$invoice_no)
{
echo $something = "something";
ob_start();
$content='<html>
<body style="padding-top: 0px">
<page>
my html content
</page><body>'.$something.'</body><html>';
$content .= ob_get_clean();
}
?>
Using the output buffer will only collect data sent to stdout after ob_start and before ob_get_clean. Your code was broken as it looks like you are trying to set the php variable $contents in html, then collecting that.
The result when you ran $contents .= ob_get_clean(); was being set to this value - which you were then passing as html to mPDF to make a pdf file from. The following is not valid html.
$content='<html>
<body style="padding-top: 0px">
<page>
my html content
</page><body>something</body><html>'
Additionally, the use of .- is to add two strings together. Since you want the $content to contain valid html, this was mucking things up.
The fix below ensures that the (valid html) content is collected into $content as it appears is your intent.
function getInvoice($conn,$uid,$id,$invoice_no) {
ob_start();
$content='<html>
<head>
<link rel="stylesheet" href="//classes.gymate.co.in/assets/bower_components/uikit/css/uikit.almost-flat.min.css" media="all">
<link rel="stylesheet" href="../assets/css/main.min.css" media="all">
<style>body{font-family:\'roboto\'; .md-card {box-shadow: none; } .uk-width-small-3-5 {width: 40%;}</style>
</head>
<body style="padding-top: 0px">
<page>
my html content
</page><body>' . "something" . '</body><html>';
echo $content;
$content = ob_get_clean();
include("../plugins/mpdf/mpdf.php");
$mpdf=new mPDF('utf-8', 'A4','','',10,10,5,5,5,5);
$mpdf->SetFont('roboto');
$mpdf->SetHTMLFooter('<p style="padding-top: 18px; font-size: 12px;"></p><p style="text-align:right; font-size: 12px;">Page {PAGENO} of {nbpg}</p></p>');
//$stylesheet = file_get_contents('../assets/css/main.min.css');
$mpdf->WriteHTML($stylesheet,1);
$mpdf->writeHTML($content);
$mpdf->Output("pdf-save-data/reciept.pdf","F");
echo "PDF File Created";
}
You can use <<<html and html to achieve this. Example is below
<?php
function getInvoice($conn,$uid,$id,$invoice_no) {
echo $something = "something";
ob_start();
$content='<html><body style="padding-top: 0px"><page>my html content</page><body>'.$something.'</body><html>';
$content .= ob_get_clean();
}
?>
Just make sure you have your single and double quotes closed correctly.
Note: Also i personally prefer not to give line breaks in the html when you are going to assgin it to a variable.
Related
I have a function that injects HTML code, the function looks like this:
function page_content() {
echo <<<HTML
<body>
<?php ?> //this won't work
</body
<style>
</style>
HTML;
}
Is there any way to write PHP code inside this HTML injection function?
This function is used for replacing the default WP Dashboard, but writing just HTML and CSS is limiting me totally :( Thanks
edit:
I have resolve this by breaking the HTML into two parts like this:
function page_content() {
echo <<<HTML
<body>
<div class="test">
<p>Body</p>
<p>Body</p>
<p>Body</p>
HTML;
echo do_shortcode('[contact-form-7 id="86" title="My Form"]');
echo <<<HTML
<p>Body</p>
<p>Body</p>
<p>Body</p>
</div>
</body>
<style>
.test {
display: flex;
flex-direction: column;
}
</style>
HTML;
}
If there is any better or easier way of doing this please let me know. I'm only learning, so always happy to learn the best ways of solving things in PHP. Thanks guys!
You can write like this.
<?php
function page_content() {
$output = 'HTML
<body>';
$output .= write php code here;
$output .=' </body
<style>
</style>
HTML';
echo output;
}
?>
I wrote like this so that you can understand easily but if you get used to combining HTML with php, you can just write together using .' and '. lol
<?php
function page_content() {
$output =
'HTML
<body>' . $write_anything_with_php .' </body>
<style>
</style>
HTML';
echo output;
}
?>
How can i return big html block with some php by using <<<HTML HTML; .
return <<<HTML
<div>Here some text</div>
<?php thisFunctionEchosomthingNotReturn(); ?>
<?php if($isflag){?>
<span>DO not do this</span>
<?php } ?>
<?php echo $whatever; ?>
HTML;
I can't understand what will work and what will not! how should i use this kind of return <<<HTML HTML; block with some php variable that i need to echo and some function that echo some thing (not return)
You can use 'capture output' for this task. see Output Control Functions
i has some example code that i have just tested. It captures the output of the div tag in $out1 and shows it again later.
This technique is used in many 'templating' libraries and in 'views' in the 'frameworks'.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test of Output control functions</title>
</head>
<body>
<?php ob_start(); // capture the buffer ?>
<div style="border: 4px solid red">
<p>This is a test paragraph</p>
<p>This is test PHP code: <?php echo time(); ?></p>
</div>
<?php $out1 = ob_get_contents(); // end capture ?>
</body>
</html>
<?php echo $out1; // output now or save for later. ?>
<?php var_dump($out1, strlen($out1)); ?>
<?php exit; ?>
Okay, google heredoc syntax for PHP.
but this is how it works (which I think you are trying to do.
$html = <<<HTML
<div>
<h1>$phpVariableTitle</h1>
<div>
{$thisFunctionEchosomthingNotReturn()}
</div>
</div>
HTML;
return $html;
Try that. IMPORTANT! heredoc syntax requires your closing tag be left aligned with no tabs. So make sure there are no spaces or tabs to the left of your heredoc tags, in this example my heredoc tags are called HTML. Also, wrapping your php variables/functions with curly braces is optional but good practice for this method. NO PHP tags in side heredoc block.
Hope that helps.
To make a conditional statement work inside you need to use a function:
class My_Class {
public function myCondition($param) {
if($param === true) {
return '<p>True</p>';
} else {
return '<p>False</p>';
}
}
}
$object =new My_Class();
$html = <<<HTML
<div>
<h1>Conditional Statement</h1>
<div> {$object->myCondition(true)} </div>
</div>
HTML;
something like that should work. But I haven't tested it.
I am unable to understand your question properly may be this may help:
<HTML>
<div>Here some text</div>
<?php thisFunctionEchosomthingNotReturn();
if($isflag){?>
<span>DO not do this</span>
<?php }//Closing If if it ends here.
echo $whatever; ?>
</HTML>
You cannot write control structures / functions logic inside of HEREDOC syntax.
Alternate way..
<div>Here some text</div>
<?php thisFunctionEchosomthingNotReturn(); ?>
<?php if($isflag){?>
<span>DO not do this</span>
<?php echo $whatever; }?>
I've got a HTML file which I've created and is stored in a directory elsewhere.
The problem is, I'd like to be able to get content externally and place it within the HTML file.
I figured I could use PHP for this, because it's server-side and can access the files I want.
So, I created a PHP script which opens and echoes a HTML file, and afterwards, echos some JavaScript to change elements that are on the screen.
Here's my PHP file:
<?php
$html = file_get_contents('file.html');
$imageurl = file_get_contents('url.txt');
$js = '<script type=\'text/javascript\'>updateImage(\'img1\', '.$imageurl.');</script>';
echo $html;
echo $js;
?>
..and the HTML file:
<html>
<script type="text/javascript">
function updateImage(id, url) {
var img = document.getElementsByName(id)[0];
img.src = url;
}
</script>
<body>
<img src="" name="img1" />
</body>
</html>
It's not the best method, but it works.
I would like to know a way to do this within PHP, not using JavaScript.
I'm not sure as of the best approach to this.
You could use include and ob_get_contents to get the html as string and do some str_replace or preg_replace on that.
Your HTML:
<html>
<body>
<img src="{IMAGE_SRC}" width="512" height="512" name="image" />
</body>
</html>
Your PHP:
ob_start();
include 'your_file.html';
$buffer = ob_get_contents();
ob_end_clean();
$buffer = str_replace('{IMAGE_SRC}', 'your_image.png', $buffer);
print $buffer;
That is a pretty basic question. You should read some PHP and HTML Tutorials. Something like this will do the trick:
<html>
<body>
<img src="" width="512" height="512" name="<?= $somePhpVariableContainingTheName ?>" />
</body>
</html>
I want to include html code inside php variables.
I remember there was a way to define html code inside a php variable, something similar to this:
<?php $my_var = { ?>
<div>SOME HTML</div>
<?php } ?>
I found it on PHP.net but I can't find it now.
There was something else instead of the "{" but I don't remember exactly.
I am looking to directly write the html code like above, so NOT like this: $my_var = '<div>SOME HTML</div>';
Any ideas?
Try this:
<?php ob_start(); ?>
<div>HTML goes here...</div>
<div>More HTML...</div>
<?php $my_var = ob_get_clean(); ?>
This way you will retain syntax highlighting for HTML.
<?php
$my_var = <<<EOD
<div>SOME HTML</div>
EOD;
?>
It's called heredoc syntax.
Save your HTML in a separate file: example.html. Then read in the contents of the file into a variable
$my_var = file_get_contents('example.html');
If you don't care about HTML syntax highlighting you could just define a normal variable. You don't have to escape HTML either because PHP lets you use single quotes to define a variable, meaning you can use double quotes within your HTML code.
$html = '
<p>
<b><i>Some html within a php variable</i><b>
</p>
<img src="path/to/some/boat.png" alt="This is an image of a boat">
' ;
Works perfectly for me, but it's a matter of preference and implementation I guess.
If you are going to be echoing the content then another way this can be done is by using functions,
this also has the added benefit of programs using syntax highlighting.
function htmlContent(){
?>
<h1>Html Content</h1>
<?php
}
htmlContent();
?>
To define HTML code inside a PHP variable:
1) Use a function (Ref: #RedSparr0w)
<?php
function htmlContent(){
?>
<h1>Html Content</h1>
<?php
}
?>
2. Store inside a variable
$var = htmlContent();
To add to the few answers that mention using a function in the var. may I suggest an anonymous function. I'm not a php wizard so please correct me if I'm wrong, but I would imagine it working something like the following:
<?php
$my_var = function(){
?>
<div>SOME HTML</div>
<?php
};
// Display content
$my_var();
To extend this even further, if other php content is needed in the html it could be passed in a few different ways.
$method1 = "Title"; // Will be the same for every instance
$method2 = "default content"; // Can change for each instance
$my_var = function($unique=$method2/*set default*/) use ($method1){
?>
<h1><?php echo $prop1; ?></h1>
<div><?php echo $unique; ?></div>
<?php
};
// Display content
$my_var();
//returns
Title
default content
$my_var("Some unique content");
//returns
Title
Some unique content
How can I use this array, in the tr, td section of html and assign this html content to a php variable $data.
$student = [
'saurabh' => 26,
'John' => 20,
'Ross' => 30
];
<!DOCTYPE html>
<html>
<head>
<style>
table{
border: 1px solid black;
}
.lft {
padding: 0px 80px 10px 5px;
}
td {
border-bottom: 2px solid black;
}
</style>
</head>
<body>
<table>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>Saurabh</td>
<td>26</td>
</tr>
</table>
</body>
</html>
i'm trying to use a jQuery show/hide script on a PHP file, and it goes like this:
<?php
foreach ($empresas as $empresa) {
echo "<style type='text/css'>
.$empresa[teaserid] {
width:100%;
background-color: #CCC;
color: #000;
margin-top:10px;
border:1px solid #CCC;
position:relative;
vertical-align:middle;
}
.showhide$empresa[teaserid] {
display:none;
}
</style>";
echo '<script type="text/javascript">';
echo ' $(document).ready(function(){ ';
echo ' $(\".$empresa[teaserid]\").hide(); ';
echo ' $(\".showhide$empresa[teaserid]\").show(); ';
echo ' $(\".showhide$empresa[teaserid]\").click(function(){ ';
echo ' $(\".$empresa[teaserid]\").slideToggle(), 500; ';
echo ' }); ';
echo ' });';
echo '</script>';
echo "<a href='#' class='showhide$empresa[teaserid]'>$empresa[titulo]</a><br />
<div class='$empresa[teaserid]'>
TEST</div>";
}
?>
So, what I need is a foreach in php that echoes new CSS values and a new jQuery script. because each DIV needs different CSS and jQuery to relate and be able to show and hide its content. This echoing didn't work. The CSS goes ok, but the jQuery doesn't with the PHP $strings. What can I do?
Or there's a simpler way to do this? A jQuery function that relates to any current div alone ?
Thanks anyone who helps me in this one..
Worth mentioning:
You can create a settings object to keep your variables in. For example:
Your php:
<?php
$settings = array( 'settingA' => 'something',
'settingB' => 'something else',
'wat' => 9001 );
?>
Keep your JS in your js file - scripts.js, whatever. But you can add this to your html file:
<script>
var settings = <?php echo json_encode( $settings ) ?>;
</script>
What will that output?
var settings = {"settingA":"something","settingB":"something else","wat":9001};
So you can put your required server info in ONE global object (or put it as a property of your application object or something) and can access it.
console.log( settings.settingA ); // returns "something"
Looking further at your question, don't forget you dont' have to stay in the PHP tags. I'm not advocating ever needing PHP in your css, but this should help you grasp the concept:
<style>
<?php foreach ($empresas as $empresa): ?>
.showhide<?php echo $empresa['teaserid'] ?> {
display:none;
}
<?php endforeach; ?>
</style>
In PHP, you can only put variables in double quote strings:
$a = 'Jon';
echo "Hi $a"; // Should output 'Hi Jon'
echo 'Hi $a'; // should output 'Hi $a'
So if you want the Javascript to read:
$(".Jon") // where Jon is the value of $a
Then in PHP you can output it this way:
echo '$(\".' . $a . '\")'; // Notice we are splitting the echo statement into a concatenation of 3 strings
There isn't really a need to have the PHP print out a new block of CSS and Javascript for each item. If you write the css and javascript is a good way, then it will all be handled for you.
One other thing to keep in mind is that PHP is at it's most basic a templating language, so if you find yourself echoing large chunks of code, you are probably being something wrong. Instead something like this:
<?php
$variable = "SOme value";
echo "Some very long huge string with <html> tags and stuff plus $variables";
?>
You can do something like this, opening and closing the tags several times.
<?php $variable = "SOme value"; ?>
Some very long huge string with <html> tags and stuff plus <?php print $variables; ?>
With that covered, here is a reworked version of your code.
As well, rather than needing to make PHP output custom Javascript with hard-coded ids, what you reall need is to structure your javascript so that it doesn't need to know ANY of that stuff at all, as I have done.
<style type='text/css'>
/* The CSS is the same, so just have one class that is used on all the items. */
.empresa-teaser {
width:100%;
background-color: #CCC;
color: #000;
margin-top:10px;
border:1px solid #CCC;
position:relative;
vertical-align:middle;
}
</style>
<script type="text/javascript">
$(function(){
// Hide all of the teasers to start.
$(".empresa-teaser").hide();
// Add a handler for when the show/hide link is clicked.
$(".showhide-empresa-teaser").click(function(){
// When it is clicked, find the next item with the 'empresa-teaser' class
// and show it using a sliding toggle effect.
$(this).nextAll('.empresa-teaser:first').slideToggle(500);
});
});
</script>
<?php foreach ($empresas as $empresa) { ?>
<a href='#' class="showhide-empresa-teaser">
<?php print $empresa['titulo']; ?>
</a>
<br />
<div class="empresa-teaser">TEST</div>
<?php } ?>