How to provide dynamic HTML in PHP? - php

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>

Related

putting html content between php function

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.

Convert all images into clickable A tags with img inside

I have a block of html with a lot of <img src="..."/> inside of it.
Now I'm looking for a way to make this:
<img src="lol.jpg"/> into:
<a href="lol.jpg" class="image_inside_text" target="_blank">
<img src="lol.jpg"/>
</a>
The idea is to make images open in a new page to view the full size image, and I'm adding a class in case I want to make it into a popup later on.
I'm looking to do this in PHP, can someone please help me?
Thank you
He asked for solution in PHP (see tags).
$string = <<<EOD
<img src="lol.jpg">
<img src="lol.jpg"/>
<img src="lol.jpg" alt="sufix"/>
<img alt="prefix" src="lol.jpg"/>
EOD;
$pattern = '/<img[^>]+src="([a-z.]+)"[^>]*>/i';
$replacement = '${0}';
echo preg_replace($pattern, $replacement, $string);
Online version: http://ideone.com/pY2EWY
Well, just use some jquery, try this :
<script>
$(function(){
$('.thisimg').replace('<img src="your src" class="thisimg" />');
});
</script>
<img src="your src" class="thisimg" />
There are several ways of doing so... Most involving Javascript.
Take a look at jquery's method wrap(), that wraps any selected element into another element:
$("img").each(function() {
var href = $(this).attr("href");
$(this).wrap("<a href='"+href+"' class='image_inside_text' target='_blank'></a>");
});
http://api.jquery.com/wrap/
You can use jQuery:
$(function(){
$('img').each(function() {
var src = $(this).attr("src");
$( this ).replaceWith('<img src="' + src + '"/>')
});
});
You can use output buffering: ob_start and do something similar to this example and replacing the callback with what test30 suggested:
<?php
function callback($buffer)
{
// replace all the apples with oranges
return (str_replace("apples", "oranges", $buffer));
}
ob_start("callback");
?>
<html>
<body>
<p>It's like comparing apples to oranges.</p>
</body>
</html>
<?php
ob_end_flush();
?>

echo text alongside a generated value PHP

I'm using this line of php in my main page
echo generateRadioButtons("fbresponse.php", "moRating1", 6);
Which when posting the following on the response file
echo $_POST['moRating1']
It works fine and displays the correct result, but! my question is how would i add text to that so..
Blah blah blah, you rated x question: 'moRating1'
I've tried doing
<html>
<head>
<title>Questions</title>
</head>
<body>
<h1>Survey responses</h1>
<p>How well did you rate it : <?php print $moRating1 ?></p>
</body>
</html>
inside the response file but that just doesnt load anything..
Any help please!
It's probably because this function uses eval() to execute its content (I guess it from lack of PHP tags in your first example).
If it's true, then you should be able to close PHP tag, print HTML and open it again.
?>
<html>
<head>
<title>Questions</title>
</head>
<body>
<h1>Survey responses</h1>
<p>How well did you rate it : <?php print $_POST['moRating1'] ?></p>
</body>
</html>
try doing:
$mRating1 = $_POST['moRating1'];
...
?>
...
<p>How well did you rate it: <?php echo $mRating1?></p>

Nested quotes level 4 javascript error

I have the following code (I formated it to more lines, but in my source code I have it in one line, because innerHTML doesn't like new lines somehow - but that isn't the problem...):
<?php
echo "
<img
src='1.png'
onclick='
document.getElementById(\"my_div\").innerHTML=\"
<img src=\\\"1.png\\\" onclick=\\\"alert(\\\\\\\"text\\\\\\\");\\\" />
\";
'
/>
";
?>
And somewhere in the body I have :
<div id="my_div"></div>
So, when I click on the image, i'll have the same image inside my_div. The problem is, that when I click on the 2nd image, javascript doesn't alert anything.
But when I change this:
alert(\\\\\\\"text\\\\\\\");
to this:
alert(MyText);
and add JavaScript variable MyText:
<script>
MyText = "text";
</script>
it now works.
I think the problem is with those nested quotes:
\\\\\\\"
(level 4). Any ideas? Thanks.
EDIT: please don't post here another methods of doing this, I'd like to know why those quotes doesn't work here..
SECOND EDIT: I need that php there, because this is only a piece of my code (in full code I need it to display images in cycle...)
If you want a quote character as data (instead of as an attribute delimiter) in HTML, you represent it as " not \"
There's nothing "dynamic" in your script - you're not inserting PHP variables, so why build that all from within a PHP echo? Simply have:
Or if you want to make it even cleaner:
<script type="text/javascript">
function addImg() {
document.getElementById('my_div').innerHTML='<img src="1.png" onclick="alert(\'text\')" />';
}
</script>
<img src="1.png" onclick="addImg()" />
refactor your JS into an external file (with a function that will do the onclick logic), and try outputting something simpler with php's echo
Use jQuery!
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<div id="my_div"></div>
<img src="1.png" class="my_img" />
<img src="2.png" class="my_img" />
<img src="3.png" class="my_img" />
<script type="text/javascript">
jQuery(function() {
$('.my_img').click(function() {
$('#my_div').html($(this).clone().unbind());
alert('text');
});
});
</script>

Showing a image created with the GC lib

i have my test.php:
<?php
echo "Image:<br/>";
include('draw.php');
?>
and my draw.php:
<?php
$img = imagecreate(250,80);
...
header("Content-type: image/jpeg"); imagejpeg($img); imagedestroy($img);
?>
now, visiting test.php tells me that headers is already sent. How do i show the image in draw.php "realtime" (not by saving to server and loading it using img tag)?
?>
If you want to incorporate this into an html page, change test.php to this:
<?php
echo "Image:<br/>";
echo '<img src="draw.php" />'
?>
You could just as easily make it a static html page:
<html>
<head>
<title>Test</title>
</head>
<body>
Images: <br />
<img src="draw.php" />
</body>
</html>
Remove echo "Image:<br/>"; from test.php and read carefully about HTTP headers http://php.net/manual/en/function.header.php so that you don't make the same mistake again

Categories