PHP spaces in HTML output when formatting code - php

Following code will produce unwanted whitespace between icons.
<div>
<img src="icon1.png" />
<img src="icon2.png" />
</div>
I need to keep image tags on single lines because I have some conditions in my .phtml file, it looks something like this:
<div>
<?php if ($condition1) : ?>
<img src="icon1.png" />
<?php endif ?>
<?php if ($condition2) : ?>
<img src="icon2.png" />
<?php endif ?>
</div>
I don't want to have all code messed up on a single line. Is there any solution for situations like this?

Apply font-size:0px; style to your div.

You may use echo to output parts of html code. You'll get something like this
<div>
<?php if (true) :
echo '<img src="icon2.png" />';
endif;
if (true) :
echo '<img src="icon2.png" />';
endif;
?>
</div>

Related

Echo an image tag with site_url() inside PHP tags

I have a loop in my view that outputs all the content gathered from the database:
<?php foreach($content as $contentRow): ?>
<?php
echo $contentRow->value;
?>
<?php endforeach; ?>
This works fine for HTML strings like:
<h2><strong>Example Text</strong></h2>
however I have some image content that I would like to display and I have tried the following database entries to no avail:
<img src="<?php echo site_url('pathToImage/Image.png'); ?>" alt="Cover">"
<img src="site_url('pathToImage/Image.png')" alt="Cover\">"
I feel like I am missing a step on how to use PHP values in this way.
How do I access the URL of the image and use that to show the image?
Full Code Edit
<?php
$CI =& get_instance();
?>
<div class="container">
<div class="row">
<div class="col-md-9">
<div class="col-md-2"></div>
<div class="col-md-20">
<!--<form class="form-center" method="post" action="<?php echo site_url(''); ?>" role="form">-->
<!-- <h2 class="">Title</h2>
<h2 class=""SubTitle/h2>-->
<?php echo $this->session->userdata('someValue'); ?>
<!--//<table class="" id="">-->
<?php foreach($content as $contentRow): ?>
<tr>
<td><?php
echo $contentRow->value;
?></td>
</tr>
<?php endforeach; ?>
<!--</table>-->
<!--</form>-->
</div>
<div class="col-md-2"></div>
</div>
</div>
</div><!-- /.container -->
and the values are being read out in $contentRow->value;
I have to verify this, but to me it looks like you are echo'ing a string with a PHP function. The function site_url() is not executed, but simply displayed. You can execute it by running the eval() function. But I have to add this function can be very dangerous and its use is not recommended.
Update:
To sum up some comments: The use of eval() is discouraged! You should reconsider / rethink your design. Maybe the use of tags which are replaced by HTML are a solution (Thanks to Manfred Radlwimmer). Always keep in mind to never trust the data you display, always filter and check!
I'm not going to accept this answer as #Philipp Palmtag's answer helped me out alot more and this is more supplementary information.
Because I'm reading data from the database it seems a sensible place to leave some information about what content is stored. In the same table that the content is stored I have added a "content type" field.
In my view I can then read this content type and render appropriately for the content that is stored. If it is just text I can leave it as HTML markup, images all I need to do is specify the file path and then I can scale this as I see fit.
I have updated my view to something akin to this and the if/else statement can be added to in the future if required:
<?php foreach($content as $contentRow): ?>
<?php if ($contentRow->type != "image"): ?>
<?php echo $contentRow->value; ?>
<?php else: ?>
<?php echo "<img src=\"".site_url($contentRow->value)."\">"; ?>
<?php endif; ?>
<?php endforeach; ?>

HTML inside php condition

The following works fine to show a source image.
<html>
<h3>First Test</h3>
<img src="example1.php" />
</html>
But I wanted to validate user, then only show source image like following,
<html>
<h3>First Test</h3>
<?php
some logic = $usermatch
if($usermatch)
<img src="example1.php" />
?>
</html>
When I try the same it simply doesn't show image and doesn't accept <img src="example1.php" /> inside the PHP code.
I am a beginner and just learning php and html.
Could you please guide me how to make it work?
Thanks.
You have to switch in and out of PHP mode
<html>
<h3>First Test</h3>
<?php if($usermatch) { ?>
<img src="example1.php" />
<?php } ?>
</html>
And some like to use echo statements, but you'll see that you get less help from editors when editing the HTML
<html>
<h3>First Test</h3>
<?php
if($usermatch)
echo '<img src="example1.php" />';
?>
A little change to your code, although this is rather an ugly way to do it.
<?php
some logic = $usermatch
if($usermatch) {
?>
<img src="example1.php" />
<?php
}
?>
Don't miss the php closing and opening tags. Try something like this
<?php
some logic = $usermatch
if($usermatch) : ?>
<img src="example1.php" />
<?php
endif;
?>
Try this:
<?php
some logic = $usermatch
if($usermatch) { ?>
<img src="example1.php" />
<?php
}
?>
The problem is that you are mixing your HTML & PHP code. It is perfectly aceptable to have HTML code in your PHP file, but you need to close the PHP code block before so that the interpreter understands that it is not code you intend to run.
Might as well add to all of the answers:
<html>
<h3>First Test</h3>
<?php echo $usermatch ? '<img src="example1.php" />' : ''; ?>
</html>
Use the following:
<html>
<h3>First Test</h3>
<?php
some logic = $usermatch
if($usermatch) {
print '<img src="example1.php" />'
}
?>
</html>
or you can use another way to print html tags in php:
<html>
<h3>First Test</h3>
<?php
some logic = $usermatch
if($usermatch) {
?>
<img src="example1.php" />
<?php } ?>
</html>

retrieve image from folder in php codeigniter

imagedisplay.php(view)
<html>
<body>
<h3>Your file was successfully uploaded!</h3>
<?php print_r($upload_data); ?> </br>
<?php $str=base_url()."images/".$upload_data['file_name'] ?> </br>
<?php $str=str_replace('http://','',$str) ?>
<?php echo $str; ?>
<img src= '$str'/> </br>
For echo $str; I got the string i need to display th image
but when i pass it to img src.... i am not able to display it on the browswer
Is there any syntactical error or am i missing anything ...pls help?
Just a small syntax problem here.
Embed PHP echo command in the HTML code, like so:
<img src="<?php echo $str; ?>"/> </br>
or embed PHP echo short tags:
<img src="<?=$str?>"/> </br>
In other words: insert the PHP output at the positions, where you need it as HTML content.

Unexpected bracket - PHP

Here is some PHP mixed with HTML, I apologize that it's quite messy.
<div class="media"><?php echo ($inf['post_url']) ?><img src="<?php echo($inf['photos'][0]['alt_sizes'][0][url]); ?>" /></div>
{block:Caption}<?php if (array_key_exists('caption', $inf))?><div class="copy"><?php Echo ($inf['caption']);?></div><?php }; ?>
<?php }; ?>
The second line produces this error
Parse error: syntax error, unexpected '}' on line 1708
I do not see anything wrong with the brackets. What is producing this error?
If you'd format your code properly so it'd actually be readable, the superfluous bracket (and missing opening bracket) would be easy to spot:
<div class="media">
<?php echo ($inf['post_url']) ?>
<img src="<?php echo($inf['photos'][0]['alt_sizes'][0][url]); ?>" />
</div>
{block:Caption}
<?php if (array_key_exists('caption', $inf))?>
<div class="copy">
<?php Echo ($inf['caption']);?>
</div>
<?php }; ?>
<?php }; ?>
It greatly helps if you indent your code correctly.
<div class="media">
<?php echo ($inf['post_url']) ?>
<img src="<?php echo($inf['photos'][0]['alt_sizes'][0][url]); ?>" />
</div>
{block:Caption}
<?php if (array_key_exists('caption', $inf)) ?>
<div class="copy">
<?php Echo ($inf['caption']);?>
</div>
<?php }; ?>
<?php }; ?>
Very basic, the closing brackets do not have corresponding opening brackets.
Some more stylistic advice: echo is a PHP construct, so you don't need to call it like a function, that is echo something is equivalent to echo(something) but the former is preferred. Also, it pays to be consistent with the capitalisation of reserved words, i.e. if you're using lowercase, always use lowercase for reserved words.
There was an extra bracket at the end as well as some superfluous semicolons, and "echo" was capitalized. Give this a shot:
<div class="media">
<?php echo ($inf['post_url']); ?>
<img src="<?php echo($inf['photos'][0]['alt_sizes'][0][url]); ?>" />
</div>
{block:Caption}
<?php if (array_key_exists('caption', $inf)) {?>
<div class="copy">
<?php echo ($inf['caption']);?>
</div>
<?php } ?>
If you boil off all the HTML, lines 2 and 3 come out to this:
if (array_key_exists('caption', $inf)) Echo ($inf['caption']); }; };
You don't need either of those closing right curly braces.

PHP - indent block of html

Let's say I have the following code:
<?php
echo "<div id=\"root\">";
echo "<div id=\"child_of_root\">";
echo "<img src=\"picture1.png\">";
echo "<img src=\"picture2.png\">";
echo "<img src=\"picture3.png\">";
echo "<img src=\"picture4.png\">";
echo "<img src=\"picture5.png\">";
echo "</div>";
echo "</div>";
?>
If I ran this the following HTML would be rendered all inline without any line breaks:
<div id="root"><div id="child_of_root"><img src="picture1.png"><img src="picture2.png"><img src="picture3.png"><img src="picture4.png"><img src="picture5.png"></div></div>
If I ran the following code:
<?php
echo "<div id=\"root\">\n";
echo "\t"."<div id=\"child_of_root\">\n";
echo "\t\t"."<img src=\"picture1.png\">"."\n";
echo "\t\t"."<img src=\"picture2.png\">"."\n";
echo "\t\t"."<img src=\"picture3.png\">"."\n";
echo "\t\t"."<img src=\"picture4.png\">"."\n";
echo "\t\t"."<img src=\"picture5.png\">"."\n";
echo "\t"."</div>"."\n";
echo "</div>";
?>
It wound render the following beautiful HTML:
<div id="root">
<div id="child_of_root">
<img src="picture1.png">
<img src="picture2.png">
<img src="picture3.png">
<img src="picture4.png">
<img src="picture5.png">
</div>
</div>
Is there a way I could achieve these beautiful indents without having to put \t before every line I want to indent. I mean so that I can indent a block instead of one line.
For one thing, it's HTML markup, so it doesn't matter how it's formatted, the browser renders it all the same. Using a tool like Firebug can give you a much better way of navigating HTML in your web-pages.
On another note, you don't have to continually use echo commands to output HTML. PHP is more-or-less a templating language in itself, so you could just exit PHP, output your HTML in your own format, and then re-enter PHP.
For example:
<?php // ... your code before this ... ?>
<div id="root">
<div id="child_of_root">
<img src="picture1.png">
<img src="picture2.png">
<img src="picture3.png">
<img src="picture4.png">
<img src="picture5.png">
</div>
</div>
<?php // ... your code after this ... ?>
If your output needs some level of dynamism to it, you can always use PHP to add in loops and whatnot.
<?php // ... your code before this ... ?>
<div id="root">
<div id="child_of_root">
<?php for ($x = 1; $x <= 5; $x++): ?>
<img src="picture<?php echo $x; ?>.png">
<?php endfor; ?>
</div>
</div>
<?php // ... your code after this ... ?>
If you still need formatted HTML, maybe for displaying code samples or something, you'll either have to continue manually using \n and \t, or you could check out the PHP Tidy extension, which is built for formatting HTML.
First of all use:
echo '<img src="picture1.png">';
instead of
echo "<img src=\"picture1.png\">";
Code is much more clear.
If you want to return HTML code in PHP, there is no other way to do indents.
However why you want to print HTML code in PHP ? Can't you just exit PHP block here ?
<?php
// do something and exit PHP block
?>
<div id="root">
<div id="child_of_root">
<img src="picture1.png">
<img src="picture2.png">
<img src="picture3.png">
<img src="picture4.png">
<img src="picture5.png">
</div>
</div>
<?php
// do again something in PHP
?>
I would suggest using HEREDOC for this. It's best for holding large blocks of HTML and Text that you wish to retain formatting:
//Note that I used spaces and not tabs, but that's only due to the post editor.
echo <<<HTML
<div id="root">
<div id="child_of_root">
<img src="picture1.png">
<img src="picture2.png">
<img src="picture3.png">
<img src="picture4.png">
<img src="picture5.png">
</div>
</div>
HTML;
You can also do
$variable = <<<OPENINGTAG
text
text
text
OPENINGTAG;
echo $variable;
Variables will also be parsed inside HEREDOC strings. Just be careful of the ending tag, it's very temperamental. No spaces before or after on it's line. I don't even know if comments are allowed.
Here it is using Dominic Barnes example with a loop:
<?php
echo <<<HTML
<div id="root">
<div id="child_of_root">
HTML;
for ($x = 1; $x <= 5; $x++)
{
echo <<<HTML
<img src="picture$x.png">
HTML;
}
echo <<<HTML
</div>
</div>
HTML;
?>
could also do:
<?php
$output = <<<HTML
<div id="root">
<div id="child_of_root">
HTML;
for ($x = 1; $x <= 5; $x++)
{
$output .= <<<HTML
<img src="picture$x.png">
HTML;
}
$output .= <<<HTML
</div>
</div>
HTML;
echo $output;
?>
NOWDOC is also available in 5.3+ which act as single quoted strings with no variable parsing.
HEREDOC and NOWDOC strings can be concatenated on to in the same way as normal strings.
If you put your picture ids in an array, you can do a foreach() loop that echoes each of the images with the new line and tab characters in front without having to code it by hand. E.g.
echo '<div id="root">\n';
echo '\t<div id="child_of_root">\n';
$images = array('picture1', 'picture2', 'picture3', 'picture4', 'picture5');
foreach ($images as $image) {
echo '\t\t<img src="'.$image.'.png">\n';
}
echo '\t</div>\n';
echo '</div>';
I tried Tidy, but for some reason no matter how I configure it, it won't seem to indent. However, somebody else has written some code that will:
PHP function for cleaning up HTML and JavaSctipt code
There are also some intelligent guidelines for avoiding the need for such code:
Get beautifully indented HTML with your PHP templates: two rules to follow
Also: fredsco.com/programming/indenting-html-output-in-php
Here is an example that worked for me:
<?php
echo '
<div style="margin-left: 100px">
<div id="root">
<div id="child_of_root">
<img src="picture1.png" /><br />
<img src="picture2.png" /><br />
<img src="picture3.png" /><br />
<img src="picture4.png" /><br />
</div>
</div>
</div>
';
?>

Categories